id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,595
|
secmon_cache.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_cache.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
void FlushEntireDataCache();
void FlushEntireDataCacheLocal();
void InvalidateEntireDataCache();
void EnsureMappingConsistency();
void EnsureMappingConsistency(uintptr_t address);
void EnsureInstructionConsistency();
| 854
|
C++
|
.inc
| 21
| 38.904762
| 76
| 0.787004
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,596
|
secmon_cache_impl.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/secmon_cache_impl.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace {
ALWAYS_INLINE int FloorLog2(int v) {
return BITSIZEOF(u32) - (hw::CountLeadingZeros(static_cast<u32>(v)) + 1);
}
ALWAYS_INLINE int CeilLog2(int v) {
const int log = FloorLog2(v);
return ((1 << log) == v) ? log : log + 1;
}
void FlushDataCacheTo(int loc) {
for (int level = 0; level < loc; ++level) {
/* Set the selection register. */
{
util::BitPack32 csselr = {};
csselr.Set<hw::CsselrEl1::InD>(0);
csselr.Set<hw::CsselrEl1::Level>(level);
HW_CPU_SET_CSSELR_EL1(csselr);
}
/* Ensure that reordering doesn't occur around this operation. */
hw::InstructionSynchronizationBarrier();
/* Get ccsidr. */
util::BitPack32 ccsidr;
HW_CPU_GET_CCSIDR_EL1(ccsidr);
/* Get cache size id info. */
const int num_sets = ccsidr.Get<hw::CcsidrEl1::NumSets>() + 1;
const int num_ways = ccsidr.Get<hw::CcsidrEl1::Associativity>() + 1;
const int line_size = ccsidr.Get<hw::CcsidrEl1::LineSize>() + 4;
const int way_shift = 32 - FloorLog2(num_ways);
const int set_shift = line_size;
for (int way = 0; way <= num_ways; way++) {
for (int set = 0; set <= num_sets; set++) {
const u64 value = (static_cast<u64>(way) << way_shift) | (static_cast<u64>(set) << set_shift) | (static_cast<u64>(level) << 1);
__asm__ __volatile__("dc cisw, %[value]" :: [value]"r"(value) : "memory");
}
}
}
}
void FlushDataCacheFrom(int loc) {
for (int level = loc - 1; level >= 0; --level) {
/* Set the selection register. */
{
util::BitPack32 csselr = {};
csselr.Set<hw::CsselrEl1::InD>(0);
csselr.Set<hw::CsselrEl1::Level>(level);
HW_CPU_SET_CSSELR_EL1(csselr);
}
/* Ensure that reordering doesn't occur around this operation. */
hw::InstructionSynchronizationBarrier();
/* Get ccsidr. */
util::BitPack32 ccsidr;
HW_CPU_GET_CCSIDR_EL1(ccsidr);
/* Get cache size id info. */
const int num_sets = ccsidr.Get<hw::CcsidrEl1::NumSets>() + 1;
const int num_ways = ccsidr.Get<hw::CcsidrEl1::Associativity>() + 1;
const int line_size = ccsidr.Get<hw::CcsidrEl1::LineSize>() + 4;
const int way_shift = 32 - FloorLog2(num_ways);
const int set_shift = line_size;
for (int way = 0; way <= num_ways; way++) {
for (int set = 0; set <= num_sets; set++) {
const u64 value = (static_cast<u64>(way) << way_shift) | (static_cast<u64>(set) << set_shift) | (static_cast<u64>(level) << 1);
__asm__ __volatile__("dc cisw, %[value]" :: [value]"r"(value) : "memory");
}
}
}
}
void InvalidateDataCacheTo(int loc) {
for (int level = 0; level < loc; ++level) {
/* Set the selection register. */
{
util::BitPack32 csselr = {};
csselr.Set<hw::CsselrEl1::InD>(0);
csselr.Set<hw::CsselrEl1::Level>(level);
HW_CPU_SET_CSSELR_EL1(csselr);
}
/* Ensure that reordering doesn't occur around this operation. */
hw::InstructionSynchronizationBarrier();
/* Get ccsidr. */
util::BitPack32 ccsidr;
HW_CPU_GET_CCSIDR_EL1(ccsidr);
/* Get cache size id info. */
const int num_sets = ccsidr.Get<hw::CcsidrEl1::NumSets>() + 1;
const int num_ways = ccsidr.Get<hw::CcsidrEl1::Associativity>() + 1;
const int line_size = ccsidr.Get<hw::CcsidrEl1::LineSize>() + 4;
const int way_shift = 32 - FloorLog2(num_ways);
const int set_shift = line_size;
for (int way = 0; way <= num_ways; way++) {
for (int set = 0; set <= num_sets; set++) {
const u64 value = (static_cast<u64>(way) << way_shift) | (static_cast<u64>(set) << set_shift) | (static_cast<u64>(level) << 1);
__asm__ __volatile__("dc isw, %[value]" :: [value]"r"(value) : "memory");
}
}
}
}
}
void FlushEntireDataCache() {
util::BitPack32 clidr;
HW_CPU_GET_CLIDR_EL1(clidr);
FlushDataCacheTo(clidr.Get<hw::ClidrEl1::Loc>());
}
void FlushEntireDataCacheLocal() {
util::BitPack32 clidr;
HW_CPU_GET_CLIDR_EL1(clidr);
FlushDataCacheFrom(clidr.Get<hw::ClidrEl1::Louis>());
}
void InvalidateEntireDataCache() {
util::BitPack32 clidr;
HW_CPU_GET_CLIDR_EL1(clidr);
InvalidateDataCacheTo(clidr.Get<hw::ClidrEl1::Loc>());
}
void EnsureMappingConsistency() {
::ams::hw::DataSynchronizationBarrierInnerShareable();
::ams::hw::InvalidateEntireTlb();
::ams::hw::DataSynchronizationBarrierInnerShareable();
::ams::hw::InstructionSynchronizationBarrier();
}
void EnsureMappingConsistency(uintptr_t address) {
::ams::hw::DataSynchronizationBarrierInnerShareable();
::ams::hw::InvalidateTlb(address);
::ams::hw::DataSynchronizationBarrierInnerShareable();
::ams::hw::InstructionSynchronizationBarrier();
}
void EnsureInstructionConsistency() {
::ams::hw::DataSynchronizationBarrierInnerShareable();
::ams::hw::InvalidateEntireInstructionCache();
::ams::hw::DataSynchronizationBarrierInnerShareable();
::ams::hw::InstructionSynchronizationBarrier();
}
| 6,354
|
C++
|
.inc
| 141
| 35.375887
| 147
| 0.578292
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,597
|
secmon_pmc_access_table_data.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_pmc_access_table_data.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
SetRegisterAllowed(APBDEV_PMC_CNTRL); /* 0x000 */
SetRegisterAllowed(APBDEV_PMC_WAKE_MASK); /* 0x00C */
SetRegisterAllowed(APBDEV_PMC_WAKE_LVL); /* 0x010 */
SetRegisterAllowed(APBDEV_PMC_WAKE_STATUS); /* 0x014 */
SetRegisterAllowed(APBDEV_PMC_DPD_PADS_ORIDE); /* 0x01C */
SetRegisterAllowed(APBDEV_PMC_DPD_SAMPLE); /* 0x020 */
SetRegisterAllowed(APBDEV_PMC_CLAMP_STATUS); /* 0x02C */
SetRegisterAllowed(APBDEV_PMC_PWRGATE_TOGGLE); /* 0x030 */
SetRegisterAllowed(APBDEV_PMC_REMOVE_CLAMPING_CMD ); /* 0x034 */
SetRegisterAllowed(APBDEV_PMC_PWRGATE_STATUS); /* 0x038 */
SetRegisterAllowed(APBDEV_PMC_PWRGOOD_TIMER); /* 0x03C */
SetRegisterAllowed(APBDEV_PMC_BLINK_TIMER); /* 0x040 */
SetRegisterAllowed(APBDEV_PMC_NO_IOPOWER); /* 0x044 */
SetRegisterAllowed(APBDEV_PMC_PWR_DET); /* 0x048 */
SetRegisterAllowed(APBDEV_PMC_AUTO_WAKE_LVL_MASK); /* 0x0DC */
SetRegisterAllowed(APBDEV_PMC_WAKE_DELAY); /* 0x0E0 */
SetRegisterAllowed(APBDEV_PMC_PWR_DET_VAL); /* 0x0E4 */
SetRegisterAllowed(APBDEV_PMC_WAKE2_MASK); /* 0x160 */
SetRegisterAllowed(APBDEV_PMC_WAKE2_LVL); /* 0x164 */
SetRegisterAllowed(APBDEV_PMC_WAKE2_STATUS); /* 0x168 */
SetRegisterAllowed(APBDEV_PMC_AUTO_WAKE2_LVL_MASK ); /* 0x170 */
SetRegisterAllowed(APBDEV_PMC_CLK_OUT_CNTRL); /* 0x1A8 */
SetRegisterAllowed(APBDEV_PMC_IO_DPD_REQ); /* 0x1B8 */
SetRegisterAllowed(APBDEV_PMC_IO_DPD_STATUS); /* 0x1BC */
SetRegisterAllowed(APBDEV_PMC_IO_DPD2_REQ); /* 0x1C0 */
SetRegisterAllowed(APBDEV_PMC_IO_DPD2_STATUS); /* 0x1C4 */
SetRegisterAllowed(APBDEV_PMC_SEL_DPD_TIM); /* 0x1C8 */
SetRegisterAllowed(APBDEV_PMC_TSC_MULT); /* 0x2B4 */
SetRegisterAllowed(APBDEV_PMC_GPU_RG_CNTRL); /* 0x2D4 */
SetRegisterAllowed(APBDEV_PMC_CNTRL2); /* 0x440 */
SetRegisterAllowed(APBDEV_PMC_WAKE_DEBOUNCE_EN); /* 0x4D8 */
| 2,650
|
C++
|
.inc
| 46
| 56.304348
| 76
| 0.682412
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,598
|
secmon_mc01_access_table_data.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_mc01_access_table_data.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
SetRegisterAllowed(MC_STAT_CONTROL); /* 0x100 */
SetRegisterAllowed(MC_STAT_EMC_CLOCK_LIMIT); /* 0x108 */
SetRegisterAllowed(MC_STAT_EMC_CLOCK_LIMIT_MSBS); /* 0x10C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_ADR_LIMIT_LO); /* 0x118 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_ADR_LIMIT_HI); /* 0x11C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_SPARE); /* 0x124 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_CLIENT_0); /* 0x128 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_CLIENT_1); /* 0x12C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_CLIENT_2); /* 0x130 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_CLIENT_3); /* 0x134 */
SetRegisterAllowed(MC_STAT_EMC_SET0_COUNT); /* 0x138 */
SetRegisterAllowed(MC_STAT_EMC_SET0_COUNT_MSBS); /* 0x13C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_ADR_LIMIT_LO); /* 0x158 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_ADR_LIMIT_HI); /* 0x15C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_SPARE); /* 0x164 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_CLIENT_0); /* 0x168 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_CLIENT_1); /* 0x16C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_CLIENT_2); /* 0x170 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_CLIENT_3); /* 0x174 */
SetRegisterAllowed(MC_STAT_EMC_SET1_COUNT); /* 0x178 */
SetRegisterAllowed(MC_STAT_EMC_SET1_COUNT_MSBS); /* 0x17C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_ADR_LIMIT_UPPER); /* 0xA20 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_ADR_LIMIT_UPPER); /* 0xA24 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_CLIENT_4); /* 0xB88 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_CLIENT_4); /* 0xB8C */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET0_CLIENT_5); /* 0xBC4 */
SetRegisterAllowed(MC_STAT_EMC_FILTER_SET1_CLIENT_5); /* 0xBC8 */
| 2,633
|
C++
|
.inc
| 42
| 61.357143
| 76
| 0.681204
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,599
|
secmon_define_pmc_access_table.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_define_pmc_access_table.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define __ACCESS_TABLE_NAME__ PmcAccessTable
#define __ACCESS_TABLE_ADDRESS__ MemoryRegionPhysicalDevicePmc.GetAddress()
#define __ACCESS_TABLE_INC__ "secmon_pmc_access_table_data.inc"
#include "secmon_define_access_table.inc"
#undef __ACCESS_TABLE_INC__
#undef __ACCESS_TABLE_ADDRESS__
#undef __ACCESS_TABLE_NAME__
| 961
|
C++
|
.inc
| 22
| 41.909091
| 76
| 0.757479
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,600
|
secmon_define_mc_access_table.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_define_mc_access_table.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define __ACCESS_TABLE_NAME__ McAccessTable
#define __ACCESS_TABLE_ADDRESS__ MemoryRegionPhysicalDeviceMemoryController.GetAddress()
#define __ACCESS_TABLE_INC__ "secmon_mc_access_table_data.inc"
#include "secmon_define_access_table.inc"
#undef __ACCESS_TABLE_INC__
#undef __ACCESS_TABLE_ADDRESS__
#undef __ACCESS_TABLE_NAME__
| 972
|
C++
|
.inc
| 22
| 42.409091
| 88
| 0.760296
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,601
|
secmon_mc_access_table_data.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_mc_access_table_data.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
SetRegisterAllowed(MC_INTSTATUS); /* 0x000 */
SetRegisterAllowed(MC_INTMASK); /* 0x004 */
SetRegisterAllowed(MC_ERR_STATUS); /* 0x008 */
SetRegisterAllowed(MC_ERR_ADR); /* 0x00C */
SetRegisterAllowed(MC_SMMU_CONFIG); /* 0x010 */
SetRegisterAllowed(MC_SMMU_PTB_ASID); /* 0x01C */
SetRegisterAllowed(MC_SMMU_PTB_DATA); /* 0x020 */
SetRegisterAllowed(MC_SMMU_TLB_FLUSH); /* 0x030 */
SetRegisterAllowed(MC_SMMU_PTC_FLUSH_0); /* 0x034 */
SetRegisterAllowed(MC_EMEM_CFG); /* 0x050 */
SetRegisterAllowed(MC_EMEM_ADR_CFG); /* 0x054 */
SetRegisterAllowed(MC_EMEM_ARB_CFG); /* 0x090 */
SetRegisterAllowed(MC_EMEM_ARB_OUTSTANDING_REQ); /* 0x094 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RCD); /* 0x098 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RP); /* 0x09C */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RC); /* 0x0A0 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RAS); /* 0x0A4 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_FAW); /* 0x0A8 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RRD); /* 0x0AC */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RAP2PRE); /* 0x0B0 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_WAP2PRE); /* 0x0B4 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_R2R); /* 0x0B8 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_W2W); /* 0x0BC */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_R2W); /* 0x0C0 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_W2R); /* 0x0C4 */
SetRegisterAllowed(MC_EMEM_ARB_MISC2); /* 0x0C8 */
SetRegisterAllowed(MC_EMEM_ARB_DA_TURNS); /* 0x0D0 */
SetRegisterAllowed(MC_EMEM_ARB_DA_COVERS); /* 0x0D4 */
SetRegisterAllowed(MC_EMEM_ARB_MISC0); /* 0x0D8 */
SetRegisterAllowed(MC_EMEM_ARB_MISC1); /* 0x0DC */
SetRegisterAllowed(MC_EMEM_ARB_RING1_THROTTLE); /* 0x0E0 */
SetRegisterAllowed(MC_CLIENT_HOTRESET_CTRL); /* 0x200 */
SetRegisterAllowed(MC_CLIENT_HOTRESET_STATUS); /* 0x204 */
SetRegisterAllowed(MC_SMMU_AFI_ASID); /* 0x238 */
SetRegisterAllowed(MC_SMMU_DC_ASID); /* 0x240 */
SetRegisterAllowed(MC_SMMU_DCB_ASID); /* 0x244 */
SetRegisterAllowed(MC_SMMU_HC_ASID); /* 0x250 */
SetRegisterAllowed(MC_SMMU_HDA_ASID); /* 0x254 */
SetRegisterAllowed(MC_SMMU_ISP2_ASID); /* 0x258 */
SetRegisterAllowed(MC_SMMU_MSENC_NVENC_ASID); /* 0x264 */
SetRegisterAllowed(MC_SMMU_NV_ASID); /* 0x268 */
SetRegisterAllowed(MC_SMMU_NV2_ASID); /* 0x26C */
SetRegisterAllowed(MC_SMMU_PPCS_ASID); /* 0x270 */
SetRegisterAllowed(MC_SMMU_SATA_ASID); /* 0x274 */
SetRegisterAllowed(MC_SMMU_VI_ASID); /* 0x280 */
SetRegisterAllowed(MC_SMMU_VIC_ASID); /* 0x284 */
SetRegisterAllowed(MC_SMMU_XUSB_HOST_ASID); /* 0x288 */
SetRegisterAllowed(MC_SMMU_XUSB_DEV_ASID); /* 0x28C */
SetRegisterAllowed(MC_SMMU_TSEC_ASID); /* 0x294 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_AVPC_0); /* 0x2E4 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_DC_0); /* 0x2E8 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_DC_1); /* 0x2EC */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_DCB_0); /* 0x2F4 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_DCB_1); /* 0x2F8 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_HC_0); /* 0x310 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_HC_1); /* 0x314 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_MPCORE_0); /* 0x320 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_NVENC_0); /* 0x328 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_PPCS_0); /* 0x344 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_PPCS_1); /* 0x348 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_ISP2_0); /* 0x370 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_ISP2_1); /* 0x374 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_XUSB_0); /* 0x37C */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_XUSB_1); /* 0x380 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_TSEC_0); /* 0x390 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_VIC_0); /* 0x394 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_VI2_0); /* 0x398 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_GPU_0); /* 0x3AC */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_SDMMCA_0); /* 0x3B8 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_SDMMCAA_0); /* 0x3BC */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_SDMMC_0); /* 0x3C0 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_SDMMCAB_0); /* 0x3C4 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_NVDEC_0); /* 0x3D8 */
SetRegisterAllowed(MC_LATENCY_ALLOWANCE_GPU2_0); /* 0x3E8 */
SetRegisterAllowed(MC_DIS_PTSA_RATE); /* 0x41C */
SetRegisterAllowed(MC_DIS_PTSA_MIN); /* 0x420 */
SetRegisterAllowed(MC_DIS_PTSA_MAX); /* 0x424 */
SetRegisterAllowed(MC_DISB_PTSA_RATE); /* 0x428 */
SetRegisterAllowed(MC_DISB_PTSA_MIN); /* 0x42C */
SetRegisterAllowed(MC_DISB_PTSA_MAX); /* 0x430 */
SetRegisterAllowed(MC_VE_PTSA_RATE); /* 0x434 */
SetRegisterAllowed(MC_VE_PTSA_MIN); /* 0x438 */
SetRegisterAllowed(MC_VE_PTSA_MAX); /* 0x43C */
SetRegisterAllowed(MC_MLL_MPCORER_PTSA_RATE); /* 0x44C */
SetRegisterAllowed(MC_RING1_PTSA_RATE); /* 0x47C */
SetRegisterAllowed(MC_RING1_PTSA_MIN); /* 0x480 */
SetRegisterAllowed(MC_RING1_PTSA_MAX); /* 0x484 */
SetRegisterAllowed(MC_PCX_PTSA_RATE); /* 0x4AC */
SetRegisterAllowed(MC_PCX_PTSA_MIN); /* 0x4B0 */
SetRegisterAllowed(MC_PCX_PTSA_MAX); /* 0x4B4 */
SetRegisterAllowed(MC_MSE_PTSA_RATE); /* 0x4C4 */
SetRegisterAllowed(MC_MSE_PTSA_MIN); /* 0x4C8 */
SetRegisterAllowed(MC_MSE_PTSA_MAX); /* 0x4CC */
SetRegisterAllowed(MC_AHB_PTSA_RATE); /* 0x4DC */
SetRegisterAllowed(MC_AHB_PTSA_MIN); /* 0x4E0 */
SetRegisterAllowed(MC_AHB_PTSA_MAX); /* 0x4E4 */
SetRegisterAllowed(MC_APB_PTSA_RATE); /* 0x4E8 */
SetRegisterAllowed(MC_APB_PTSA_MIN); /* 0x4EC */
SetRegisterAllowed(MC_APB_PTSA_MAX); /* 0x4F0 */
SetRegisterAllowed(MC_FTOP_PTSA_RATE); /* 0x50C */
SetRegisterAllowed(MC_HOST_PTSA_RATE); /* 0x518 */
SetRegisterAllowed(MC_HOST_PTSA_MIN); /* 0x51C */
SetRegisterAllowed(MC_HOST_PTSA_MAX); /* 0x520 */
SetRegisterAllowed(MC_USBX_PTSA_RATE); /* 0x524 */
SetRegisterAllowed(MC_USBX_PTSA_MIN); /* 0x528 */
SetRegisterAllowed(MC_USBX_PTSA_MAX); /* 0x52C */
SetRegisterAllowed(MC_USBD_PTSA_RATE); /* 0x530 */
SetRegisterAllowed(MC_USBD_PTSA_MIN); /* 0x534 */
SetRegisterAllowed(MC_USBD_PTSA_MAX); /* 0x538 */
SetRegisterAllowed(MC_GK_PTSA_RATE); /* 0x53C */
SetRegisterAllowed(MC_GK_PTSA_MIN); /* 0x540 */
SetRegisterAllowed(MC_GK_PTSA_MAX); /* 0x544 */
SetRegisterAllowed(MC_AUD_PTSA_RATE); /* 0x548 */
SetRegisterAllowed(MC_AUD_PTSA_MIN); /* 0x54C */
SetRegisterAllowed(MC_AUD_PTSA_MAX); /* 0x550 */
SetRegisterAllowed(MC_VICPC_PTSA_RATE); /* 0x554 */
SetRegisterAllowed(MC_VICPC_PTSA_MIN); /* 0x558 */
SetRegisterAllowed(MC_VICPC_PTSA_MAX); /* 0x55C */
SetRegisterAllowed(MC_JPG_PTSA_RATE); /* 0x584 */
SetRegisterAllowed(MC_JPG_PTSA_MIN); /* 0x588 */
SetRegisterAllowed(MC_JPG_PTSA_MAX); /* 0x58C */
SetRegisterAllowed(MC_GK2_PTSA_RATE); /* 0x610 */
SetRegisterAllowed(MC_GK2_PTSA_MIN); /* 0x614 */
SetRegisterAllowed(MC_GK2_PTSA_MAX); /* 0x618 */
SetRegisterAllowed(MC_SDM_PTSA_RATE); /* 0x61C */
SetRegisterAllowed(MC_SDM_PTSA_MIN); /* 0x620 */
SetRegisterAllowed(MC_SDM_PTSA_MAX); /* 0x624 */
SetRegisterAllowed(MC_HDAPC_PTSA_RATE); /* 0x628 */
SetRegisterAllowed(MC_HDAPC_PTSA_MIN); /* 0x62C */
SetRegisterAllowed(MC_HDAPC_PTSA_MAX); /* 0x630 */
SetRegisterAllowed(MC_SEC_CARVEOUT_BOM); /* 0x670 */
SetRegisterAllowed(MC_SEC_CARVEOUT_SIZE_MB); /* 0x674 */
SetRegisterAllowed(MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0A); /* 0x690 */
SetRegisterAllowed(MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0AB); /* 0x694 */
SetRegisterAllowed(MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0B); /* 0x698 */
SetRegisterAllowed(MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0BB); /* 0x69C */
SetRegisterAllowed(MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0C); /* 0x6A0 */
SetRegisterAllowed(MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0CB); /* 0x6A4 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_RFCPB); /* 0x6C0 */
SetRegisterAllowed(MC_EMEM_ARB_TIMING_CCDMW); /* 0x6C4 */
SetRegisterAllowed(MC_EMEM_ARB_REFPB_HP_CTRL); /* 0x6F0 */
SetRegisterAllowed(MC_EMEM_ARB_REFPB_BANK_CTRL); /* 0x6F4 */
SetRegisterAllowed(MC_PTSA_GRANT_DECREMENT); /* 0x960 */
SetRegisterAllowed(MC_CLIENT_HOTRESET_CTRL_1); /* 0x970 */
SetRegisterAllowed(MC_CLIENT_HOTRESET_STATUS_1); /* 0x974 */
SetRegisterAllowed(MC_SMMU_PTC_FLUSH_1); /* 0x9B8 */
SetRegisterAllowed(MC_SMMU_DC1_ASID); /* 0xA88 */
SetRegisterAllowed(MC_SMMU_SDMMC1A_ASID); /* 0xA94 */
SetRegisterAllowed(MC_SMMU_SDMMC2A_ASID); /* 0xA98 */
SetRegisterAllowed(MC_SMMU_SDMMC3A_ASID); /* 0xA9C */
SetRegisterAllowed(MC_SMMU_SDMMC4A_ASID); /* 0xAA0 */
SetRegisterAllowed(MC_SMMU_ISP2B_ASID); /* 0xAA4 */
SetRegisterAllowed(MC_SMMU_GPU_ASID); /* 0xAA8 */
SetRegisterAllowed(MC_SMMU_GPUB_ASID); /* 0xAAC */
SetRegisterAllowed(MC_SMMU_PPCS2_ASID); /* 0xAB0 */
SetRegisterAllowed(MC_SMMU_NVDEC_ASID); /* 0xAB4 */
SetRegisterAllowed(MC_SMMU_APE_ASID); /* 0xAB8 */
SetRegisterAllowed(MC_SMMU_SE_ASID); /* 0xABC */
SetRegisterAllowed(MC_SMMU_NVJPG_ASID); /* 0xAC0 */
SetRegisterAllowed(MC_SMMU_HC1_ASID); /* 0xAC4 */
SetRegisterAllowed(MC_SMMU_SE1_ASID); /* 0xAC8 */
SetRegisterAllowed(MC_SMMU_AXIAP_ASID); /* 0xACC */
SetRegisterAllowed(MC_SMMU_ETR_ASID); /* 0xAD0 */
SetRegisterAllowed(MC_SMMU_TSECB_ASID); /* 0xAD4 */
SetRegisterAllowed(MC_SMMU_TSEC1_ASID); /* 0xAD8 */
SetRegisterAllowed(MC_SMMU_TSECB1_ASID); /* 0xADC */
SetRegisterAllowed(MC_SMMU_NVDEC1_ASID); /* 0xAE0 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_CTRL); /* 0xBCC */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_0); /* 0xBD0 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_1); /* 0xBD4 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_2); /* 0xBD8 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_3); /* 0xBDC */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_4); /* 0xBE0 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_5); /* 0xBE4 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_6); /* 0xBE8 */
SetRegisterAllowed(MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_7); /* 0xBEC */
SetRegisterAllowed(MC_ERR_GENERALIZED_CARVEOUT_STATUS); /* 0xC00 */
SetRegisterAllowed(MC_SECURITY_CARVEOUT2_BOM); /* 0xC5C */
SetRegisterAllowed(MC_SECURITY_CARVEOUT3_BOM); /* 0xCAC */
| 13,881
|
C++
|
.inc
| 194
| 70.479381
| 76
| 0.558048
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,602
|
secmon_define_access_table.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_define_access_table.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using __ACCESS_TABLE_NAME__ = AccessTable<__ACCESS_TABLE_ADDRESS__, [] {
/* Declare a table. */
std::array<u8, 0x80> table = {};
/* Declare a helper. */
auto SetRegisterAllowed = [&](uintptr_t reg) { SetRegisterTableAllowed(table, reg); };
/* Populate the table. */
#include __ACCESS_TABLE_INC__
return table;
}()>;
static_assert(__ACCESS_TABLE_NAME__::Address >= __ACCESS_TABLE_ADDRESS__);
| 1,087
|
C++
|
.inc
| 25
| 39.48
| 94
| 0.688742
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,603
|
secmon_define_mc01_access_table.inc
|
Atmosphere-NX_Atmosphere/exosphere/program/source/smc/secmon_define_mc01_access_table.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define __ACCESS_TABLE_NAME__ Mc01AccessTable
#define __ACCESS_TABLE_ADDRESS__ 0
#define __ACCESS_TABLE_INC__ "secmon_mc01_access_table_data.inc"
#include "secmon_define_access_table.inc"
#undef __ACCESS_TABLE_INC__
#undef __ACCESS_TABLE_ADDRESS__
#undef __ACCESS_TABLE_NAME__
| 922
|
C++
|
.inc
| 22
| 40.136364
| 76
| 0.750279
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,604
|
fatal_display_config.inc
|
Atmosphere-NX_Atmosphere/exosphere/mariko_fatal/source/fatal_display_config.inc
|
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
struct RegisterWrite {
u32 offset;
u32 value;
};
enum SleepOrRegisterWriteKind : u16 {
SleepOrRegisterWriteKind_Write = 0,
SleepOrRegisterWriteKind_Sleep = 1,
};
struct SleepOrRegisterWrite {
SleepOrRegisterWriteKind kind;
u16 offset;
u32 value;
};
constexpr const RegisterWrite DisplayConfigPlld01Erista[] = {
{CLK_RST_CONTROLLER_CLK_SOURCE_DISP1, 0x40000000},
{CLK_RST_CONTROLLER_PLLD_BASE, 0x4830A001},
{CLK_RST_CONTROLLER_PLLD_MISC1, 0x00000020},
{CLK_RST_CONTROLLER_PLLD_MISC, 0x002D0AAA},
};
constexpr const RegisterWrite DisplayConfigPlld01Mariko[] = {
{CLK_RST_CONTROLLER_CLK_SOURCE_DISP1, 0x40000000},
{CLK_RST_CONTROLLER_PLLD_BASE, 0x4830A001},
{CLK_RST_CONTROLLER_PLLD_MISC1, 0x00000000},
{CLK_RST_CONTROLLER_PLLD_MISC, 0x002DFC00},
};
constexpr const SleepOrRegisterWrite DisplayConfigDc01[] = {
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_REG_ACT_CONTROL, 0x54},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_DISP_DC_MCCIF_FIFOCTRL, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_MEM_HIGH_PRIORITY, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_MEM_HIGH_PRIORITY_TIMER, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_POWER_CONTROL, PW0_ENABLE | PW1_ENABLE | PW2_ENABLE | PW3_ENABLE | PW4_ENABLE | PM0_ENABLE | PM1_ENABLE},
{SleepOrRegisterWriteKind_Write, DC_CMD_GENERAL_INCR_SYNCPT_CNTRL, SYNCPT_CNTRL_NO_STALL},
{SleepOrRegisterWriteKind_Write, DC_CMD_CONT_SYNCPT_VSYNC, SYNCPT_VSYNC_ENABLE | 0x9}, // 9: SYNCPT
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE | WIN_A_UPDATE | WIN_B_UPDATE | WIN_C_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ | WIN_A_ACT_REQ | WIN_B_ACT_REQ | WIN_C_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_DV_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
/* Setup default YUV colorspace conversion coefficients */
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_YOF, 0xF0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KYRGB, 0x12A},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUR, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVR, 0x198},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUG, 0x39B},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVG, 0x32F},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUB, 0x204},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVB, 0},
/* End of color coefficients */
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_DV_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
/* Setup default YUV colorspace conversion coefficients */
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_YOF, 0xF0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KYRGB, 0x12A},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUR, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVR, 0x198},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUG, 0x39B},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVG, 0x32F},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUB, 0x204},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVB, 0},
/* End of color coefficients */
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_DV_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
/* Setup default YUV colorspace conversion coefficients */
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_YOF, 0xF0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KYRGB, 0x12A},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUR, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVR, 0x198},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUG, 0x39B},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVG, 0x32F},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUB, 0x204},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVB, 0},
/* End of color coefficients */
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_COLOR_CONTROL, BASE_COLOR_SIZE_888},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_INTERFACE_CONTROL, DISP_DATA_FORMAT_DF1P1C},
{SleepOrRegisterWriteKind_Write, DC_COM_PIN_OUTPUT_POLARITY(1), 0x1000000},
{SleepOrRegisterWriteKind_Write, DC_COM_PIN_OUTPUT_POLARITY(3), 0},
{SleepOrRegisterWriteKind_Write, 0x4E4, 0},
{SleepOrRegisterWriteKind_Write, DC_COM_CRC_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE | WIN_A_UPDATE | WIN_B_UPDATE | WIN_C_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ | WIN_A_ACT_REQ | WIN_B_ACT_REQ | WIN_C_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, 0x716, 0x10000FF},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, 0x716, 0x10000FF},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, 0x716, 0x10000FF},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND_OPTION0, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE | WIN_A_UPDATE | WIN_B_UPDATE | WIN_C_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ | WIN_A_ACT_REQ | WIN_B_ACT_REQ | WIN_C_ACT_REQ}
};
constexpr const RegisterWrite DisplayConfigDsi01Init01[] = {
{sizeof(u32) * DSI_WR_DATA, 0x0},
{sizeof(u32) * DSI_INT_ENABLE, 0x0},
{sizeof(u32) * DSI_INT_STATUS, 0x0},
{sizeof(u32) * DSI_INT_MASK, 0x0},
{sizeof(u32) * DSI_INIT_SEQ_DATA_0, 0x0},
{sizeof(u32) * DSI_INIT_SEQ_DATA_1, 0x0},
{sizeof(u32) * DSI_INIT_SEQ_DATA_2, 0x0},
{sizeof(u32) * DSI_INIT_SEQ_DATA_3, 0x0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init02Erista[] = {
{sizeof(u32) * DSI_INIT_SEQ_DATA_15, 0x0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init02Mariko[] = {
{sizeof(u32) * DSI_INIT_SEQ_DATA_15_MARIKO, 0x0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init03[] = {
{sizeof(u32) * DSI_DCS_CMDS, 0},
{sizeof(u32) * DSI_PKT_SEQ_0_LO, 0},
{sizeof(u32) * DSI_PKT_SEQ_1_LO, 0},
{sizeof(u32) * DSI_PKT_SEQ_2_LO, 0},
{sizeof(u32) * DSI_PKT_SEQ_3_LO, 0},
{sizeof(u32) * DSI_PKT_SEQ_4_LO, 0},
{sizeof(u32) * DSI_PKT_SEQ_5_LO, 0},
{sizeof(u32) * DSI_PKT_SEQ_0_HI, 0},
{sizeof(u32) * DSI_PKT_SEQ_1_HI, 0},
{sizeof(u32) * DSI_PKT_SEQ_2_HI, 0},
{sizeof(u32) * DSI_PKT_SEQ_3_HI, 0},
{sizeof(u32) * DSI_PKT_SEQ_4_HI, 0},
{sizeof(u32) * DSI_PKT_SEQ_5_HI, 0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init04Erista[] = {
/* No register writes. */
};
constexpr const RegisterWrite DisplayConfigDsi01Init04Mariko[] = {
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
{sizeof(u32) * DSI_PAD_CONTROL_2, 0},
{sizeof(u32) * DSI_PAD_CONTROL_3, 0},
{sizeof(u32) * DSI_PAD_CONTROL_4, 0},
{sizeof(u32) * DSI_PAD_CONTROL_5_MARIKO, 0},
{sizeof(u32) * DSI_PAD_CONTROL_6_MARIKO, 0},
{sizeof(u32) * DSI_PAD_CONTROL_7_MARIKO, 0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init05[] = {
{sizeof(u32) * DSI_PAD_CONTROL_CD, 0},
{sizeof(u32) * DSI_SOL_DELAY, 0x18},
{sizeof(u32) * DSI_MAX_THRESHOLD, 0x1E0},
{sizeof(u32) * DSI_TRIGGER, 0},
{sizeof(u32) * DSI_INIT_SEQ_CONTROL, 0},
{sizeof(u32) * DSI_PKT_LEN_0_1, 0},
{sizeof(u32) * DSI_PKT_LEN_2_3, 0},
{sizeof(u32) * DSI_PKT_LEN_4_5, 0},
{sizeof(u32) * DSI_PKT_LEN_6_7, 0},
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init06[] = {
{sizeof(u32) * DSI_PHY_TIMING_1, 0x40A0E05},
{sizeof(u32) * DSI_PHY_TIMING_2, 0x30109},
{sizeof(u32) * DSI_BTA_TIMING, 0x190A14},
{sizeof(u32) * DSI_TIMEOUT_0, DSI_TIMEOUT_LRX(0x2000) | DSI_TIMEOUT_HTX(0xFFFF)},
{sizeof(u32) * DSI_TIMEOUT_1, DSI_TIMEOUT_PR(0x765) | DSI_TIMEOUT_TA(0x2000)},
{sizeof(u32) * DSI_TO_TALLY, 0},
{sizeof(u32) * DSI_PAD_CONTROL_0, DSI_PAD_CONTROL_VS1_PULLDN(0) | DSI_PAD_CONTROL_VS1_PDIO(0)}, // Enable
{sizeof(u32) * DSI_POWER_CONTROL, DSI_POWER_CONTROL_ENABLE},
{sizeof(u32) * DSI_POWER_CONTROL, DSI_POWER_CONTROL_ENABLE},
{sizeof(u32) * DSI_POWER_CONTROL, 0},
{sizeof(u32) * DSI_POWER_CONTROL, 0},
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init07[] = {
{sizeof(u32) * DSI_PHY_TIMING_1, 0x40A0E05},
{sizeof(u32) * DSI_PHY_TIMING_2, 0x30118},
{sizeof(u32) * DSI_BTA_TIMING, 0x190A14},
{sizeof(u32) * DSI_TIMEOUT_0, DSI_TIMEOUT_LRX(0x2000) | DSI_TIMEOUT_HTX(0xFFFF)},
{sizeof(u32) * DSI_TIMEOUT_1, DSI_TIMEOUT_PR(0x1343) | DSI_TIMEOUT_TA(0x2000)},
{sizeof(u32) * DSI_TO_TALLY, 0},
{sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_CRC_RESET | DSI_HOST_CONTROL_TX_TRIG_HOST | DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC},
{sizeof(u32) * DSI_CONTROL, DSI_CONTROL_LANES(3) | DSI_CONTROL_HOST_ENABLE},
{sizeof(u32) * DSI_POWER_CONTROL, DSI_POWER_CONTROL_ENABLE},
{sizeof(u32) * DSI_POWER_CONTROL, DSI_POWER_CONTROL_ENABLE},
{sizeof(u32) * DSI_MAX_THRESHOLD, 0x40},
{sizeof(u32) * DSI_TRIGGER, 0},
{sizeof(u32) * DSI_TX_CRC, 0},
{sizeof(u32) * DSI_INIT_SEQ_CONTROL, 0}
};
constexpr const RegisterWrite DisplayConfigDsiPhyTimingErista[] = {
{sizeof(u32) * DSI_PHY_TIMING_0, 0x6070601},
};
constexpr const RegisterWrite DisplayConfigDsiPhyTimingMariko[] = {
{sizeof(u32) * DSI_PHY_TIMING_0, 0x6070603},
};
constexpr const SleepOrRegisterWrite DisplayConfigJdiSpecificInit01[] = {
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x439},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x9483FFB9},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xBD15},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x1939},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAAAAAAD8},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAAAAAAEB},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAAEBAAAA},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAAAAAAAA},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAAAAAAEB},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAAEBAAAA},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xAA},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x1BD15},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2739},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFD8},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2BD15},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xF39},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFD8},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xFFFFFF},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xBD15},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x6D915},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x439},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xB9},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x1105},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Sleep, 180, 0},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2905},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
};
constexpr const RegisterWrite DisplayConfigPlld02Erista[] = {
{CLK_RST_CONTROLLER_PLLD_BASE, 0x4810c001},
{CLK_RST_CONTROLLER_PLLD_MISC1, 0x00000020},
{CLK_RST_CONTROLLER_PLLD_MISC, 0x002D0AAA},
};
constexpr const RegisterWrite DisplayConfigPlld02Mariko[] = {
{CLK_RST_CONTROLLER_PLLD_BASE, 0x4810c001},
{CLK_RST_CONTROLLER_PLLD_MISC1, 0x00000000},
{CLK_RST_CONTROLLER_PLLD_MISC, 0x002DFC00},
};
constexpr const RegisterWrite DisplayConfigDsi01Init08[] = {
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
};
constexpr const SleepOrRegisterWrite DisplayConfigDsi01Init09[] = {
{SleepOrRegisterWriteKind_Write, DSI_PHY_TIMING_1, 0x40A0E05},
{SleepOrRegisterWriteKind_Write, DSI_PHY_TIMING_2, 0x30172},
{SleepOrRegisterWriteKind_Write, DSI_BTA_TIMING, 0x190A14},
{SleepOrRegisterWriteKind_Write, DSI_TIMEOUT_0, DSI_TIMEOUT_LRX(0x2000) | DSI_TIMEOUT_HTX(0xA40)},
{SleepOrRegisterWriteKind_Write, DSI_TIMEOUT_1, DSI_TIMEOUT_PR(0x5A2F) | DSI_TIMEOUT_TA(0x2000)},
{SleepOrRegisterWriteKind_Write, DSI_TO_TALLY, 0},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_0_LO, 0x40000208},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_2_LO, 0x40000308},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_4_LO, 0x40000308},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_1_LO, 0x40000308},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_3_LO, 0x3F3B2B08},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_3_HI, 0x2CC},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_5_LO, 0x3F3B2B08},
{SleepOrRegisterWriteKind_Write, DSI_PKT_SEQ_5_HI, 0x2CC},
{SleepOrRegisterWriteKind_Write, DSI_PKT_LEN_0_1, 0xCE0000},
{SleepOrRegisterWriteKind_Write, DSI_PKT_LEN_2_3, 0x87001A2},
{SleepOrRegisterWriteKind_Write, DSI_PKT_LEN_4_5, 0x190},
{SleepOrRegisterWriteKind_Write, DSI_PKT_LEN_6_7, 0x190},
{SleepOrRegisterWriteKind_Write, DSI_HOST_CONTROL, 0},
};
constexpr const RegisterWrite DisplayConfigDsi01Init10[] = {
{sizeof(u32) * DSI_TRIGGER, 0},
{sizeof(u32) * DSI_CONTROL, 0},
{sizeof(u32) * DSI_SOL_DELAY, 6},
{sizeof(u32) * DSI_MAX_THRESHOLD, 0x1E0},
{sizeof(u32) * DSI_POWER_CONTROL, DSI_POWER_CONTROL_ENABLE},
{sizeof(u32) * DSI_CONTROL, DSI_CONTROL_HS_CLK_CTRL | DSI_CONTROL_FORMAT(3) | DSI_CONTROL_LANES(3) | DSI_CONTROL_VIDEO_ENABLE},
{sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_HS | DSI_HOST_CONTROL_FIFO_SEL | DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC},
{sizeof(u32) * DSI_CONTROL, DSI_CONTROL_HS_CLK_CTRL | DSI_CONTROL_FORMAT(3) | DSI_CONTROL_LANES(3) | DSI_CONTROL_VIDEO_ENABLE},
{sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC},
{sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_HS | DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC}
};
constexpr const RegisterWrite DisplayConfigDsi01Init11Erista[] = {
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
{sizeof(u32) * DSI_PAD_CONTROL_2, 0},
{sizeof(u32) * DSI_PAD_CONTROL_3, DSI_PAD_PREEMP_PD_CLK(0x3) | DSI_PAD_PREEMP_PU_CLK(0x3) | DSI_PAD_PREEMP_PD(0x03) | DSI_PAD_PREEMP_PU(0x3)},
{sizeof(u32) * DSI_PAD_CONTROL_4, 0}
};
constexpr const RegisterWrite DisplayConfigDsi01Init11Mariko[] = {
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
{sizeof(u32) * DSI_PAD_CONTROL_2, 0},
{sizeof(u32) * DSI_PAD_CONTROL_3, 0},
{sizeof(u32) * DSI_PAD_CONTROL_4, 0x77777},
{sizeof(u32) * DSI_PAD_CONTROL_5_MARIKO, 0x77777},
{sizeof(u32) * DSI_PAD_CONTROL_6_MARIKO, DSI_PAD_PREEMP_PD_CLK(0x1) | DSI_PAD_PREEMP_PU_CLK(0x1) | DSI_PAD_PREEMP_PD(0x01) | DSI_PAD_PREEMP_PU(0x1)},
{sizeof(u32) * DSI_PAD_CONTROL_7_MARIKO, 0},
};
constexpr const RegisterWrite DisplayConfigMipiCal01[] = {
{MIPI_CAL_MIPI_BIAS_PAD_CFG2, 0},
{MIPI_CAL_CIL_MIPI_CAL_STATUS, 0xF3F10000},
{MIPI_CAL_MIPI_BIAS_PAD_CFG0, 1},
{MIPI_CAL_MIPI_BIAS_PAD_CFG2, 0},
};
constexpr const RegisterWrite DisplayConfigMipiCal02Erista[] = {
{MIPI_CAL_MIPI_BIAS_PAD_CFG2, 0x10010},
{MIPI_CAL_MIPI_BIAS_PAD_CFG1, 0x300},
};
constexpr const RegisterWrite DisplayConfigMipiCal02Mariko[] = {
{MIPI_CAL_MIPI_BIAS_PAD_CFG2, 0x10010},
{MIPI_CAL_MIPI_BIAS_PAD_CFG1, 0},
};
constexpr const RegisterWrite DisplayConfigMipiCal03Erista[] = {
{MIPI_CAL_DSIA_MIPI_CAL_CONFIG, 0x200200},
{MIPI_CAL_DSIB_MIPI_CAL_CONFIG, 0x200200},
{MIPI_CAL_DSIA_MIPI_CAL_CONFIG_2, 0x200002},
{MIPI_CAL_DSIB_MIPI_CAL_CONFIG_2, 0x200002},
{MIPI_CAL_CILA_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_CILB_MIPI_CAL_CONFIG, 0},
};
constexpr const RegisterWrite DisplayConfigMipiCal03Mariko[] = {
{MIPI_CAL_DSIA_MIPI_CAL_CONFIG, 0x200006},
{MIPI_CAL_DSIB_MIPI_CAL_CONFIG, 0x200006},
{MIPI_CAL_DSIA_MIPI_CAL_CONFIG_2, 0x260000},
{MIPI_CAL_DSIB_MIPI_CAL_CONFIG_2, 0x260000},
{MIPI_CAL_CILA_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_CILB_MIPI_CAL_CONFIG, 0},
};
constexpr const RegisterWrite DisplayConfigMipiCal04[] = {
{MIPI_CAL_CILC_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_CILD_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_CILE_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_CILF_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_DSIC_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_DSID_MIPI_CAL_CONFIG, 0},
{MIPI_CAL_DSIB_MIPI_CAL_CONFIG_2, 0},
{MIPI_CAL_DSIC_MIPI_CAL_CONFIG_2, 0},
{MIPI_CAL_DSID_MIPI_CAL_CONFIG_2, 0},
{MIPI_CAL_MIPI_CAL_CTRL, 0x2A000001},
};
constexpr const SleepOrRegisterWrite DisplayConfigDc02[] = {
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_DV_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
/* Setup default YUV colorspace conversion coefficients */
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_YOF, 0xF0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KYRGB, 0x12A},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUR, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVR, 0x198},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUG, 0x39B},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVG, 0x32F},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUB, 0x204},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVB, 0},
/* End of color coefficients */
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_DV_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
/* Setup default YUV colorspace conversion coefficients */
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_YOF, 0xF0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KYRGB, 0x12A},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUR, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVR, 0x198},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUG, 0x39B},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVG, 0x32F},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUB, 0x204},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVB, 0},
/* End of color coefficients */
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_DV_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
/* Setup default YUV colorspace conversion coefficients */
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_YOF, 0xF0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KYRGB, 0x12A},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUR, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVR, 0x198},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUG, 0x39B},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVG, 0x32F},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KUB, 0x204},
{SleepOrRegisterWriteKind_Write, DC_WIN_CSC_KVB, 0},
/* End of color coefficients */
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_COLOR_CONTROL, BASE_COLOR_SIZE_888},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_INTERFACE_CONTROL, DISP_DATA_FORMAT_DF1P1C},
{SleepOrRegisterWriteKind_Write, DC_COM_PIN_OUTPUT_POLARITY(1), 0x1000000},
{SleepOrRegisterWriteKind_Write, DC_COM_PIN_OUTPUT_POLARITY(3), 0},
{SleepOrRegisterWriteKind_Write, 0x4E4, 0},
{SleepOrRegisterWriteKind_Write, DC_COM_CRC_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE | WIN_A_UPDATE | WIN_B_UPDATE | WIN_C_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ | WIN_A_ACT_REQ | WIN_B_ACT_REQ | WIN_C_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, 0x716, 0x10000FF},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, 0x716, 0x10000FF},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, 0x716, 0x10000FF},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND_OPTION0, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE | WIN_A_UPDATE | WIN_B_UPDATE | WIN_C_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ | WIN_A_ACT_REQ | WIN_B_ACT_REQ | WIN_C_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, 0},
/* Set Display timings */
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_TIMING_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_REF_TO_SYNC, (1 << 16)}, // h_ref_to_sync = 0, v_ref_to_sync = 1.
{SleepOrRegisterWriteKind_Write, DC_DISP_SYNC_WIDTH, 0x10048},
{SleepOrRegisterWriteKind_Write, DC_DISP_BACK_PORCH, 0x90048},
{SleepOrRegisterWriteKind_Write, DC_DISP_ACTIVE, 0x50002D0},
{SleepOrRegisterWriteKind_Write, DC_DISP_FRONT_PORCH, 0xA0088}, // Sources say that this should be above the DC_DISP_ACTIVE cmd.
/* End of Display timings */
{SleepOrRegisterWriteKind_Write, DC_DISP_SHIFT_CLOCK_OPTIONS, SC1_H_QUALIFIER_NONE | SC0_H_QUALIFIER_NONE},
{SleepOrRegisterWriteKind_Write, DC_COM_PIN_OUTPUT_ENABLE(1), 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DATA_ENABLE_OPTIONS, DE_SELECT_ACTIVE | DE_CONTROL_NORMAL},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_INTERFACE_CONTROL, DISP_DATA_FORMAT_DF1P1C},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_CLOCK_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND_OPTION0, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND, DISP_CTRL_MODE_C_DISPLAY},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, READ_MUX | WRITE_MUX},
{SleepOrRegisterWriteKind_Write, DC_DISP_FRONT_PORCH, 0xA0088},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_GENERAL_INCR_SYNCPT, 0x301},
{SleepOrRegisterWriteKind_Write, DC_CMD_GENERAL_INCR_SYNCPT, 0x301},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_ACCESS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_CLOCK_CONTROL, PIXEL_CLK_DIVIDER_PCD1 | SHIFT_CLK_DIVIDER(4)},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_COLOR_CONTROL, BASE_COLOR_SIZE_888},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND_OPTION0, 0}
};
constexpr u32 DisplayConfigFrameBufferAddress = 0xC0000000;
constexpr const SleepOrRegisterWrite DisplayConfigFrameBuffer[] = {
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_C_SELECT}, //Enable window C.
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_B_SELECT}, //Enable window B.
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_WINDOW_HEADER, WINDOW_A_SELECT}, //Enable window A.
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, DSI_ENABLE}, //DSI_ENABLE
{SleepOrRegisterWriteKind_Write, DC_WIN_COLOR_DEPTH, WIN_COLOR_DEPTH_B8G8R8A8}, //T_A8R8G8B8 //NX Default: T_A8B8G8R8, WIN_COLOR_DEPTH_R8G8B8A8
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_POSITION, 0}, //(0,0)
{SleepOrRegisterWriteKind_Write, DC_WIN_H_INITIAL_DDA, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_V_INITIAL_DDA, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_PRESCALED_SIZE, V_PRESCALED_SIZE(1280) | H_PRESCALED_SIZE(2880)}, //Pre-scaled size: 1280x2880 bytes.
{SleepOrRegisterWriteKind_Write, DC_WIN_DDA_INC, V_DDA_INC(0x1000) | H_DDA_INC(0x1000)},
{SleepOrRegisterWriteKind_Write, DC_WIN_SIZE, V_SIZE(1280) | H_SIZE(720)}, //Window size: 1280 vertical lines x 720 horizontal pixels.
{SleepOrRegisterWriteKind_Write, DC_WIN_LINE_STRIDE, 0x6000C00}, //768*2x768*4 (= 0x600 x 0xC00) bytes, see TRM for alignment requirements.
{SleepOrRegisterWriteKind_Write, DC_WIN_BUFFER_CONTROL, 0},
{SleepOrRegisterWriteKind_Write, DC_WINBUF_SURFACE_KIND, 0}, //Regular surface.
{SleepOrRegisterWriteKind_Write, DC_WINBUF_START_ADDR, DisplayConfigFrameBufferAddress}, //Framebuffer address.
{SleepOrRegisterWriteKind_Write, DC_WINBUF_ADDR_H_OFFSET, 0},
{SleepOrRegisterWriteKind_Write, DC_WINBUF_ADDR_V_OFFSET, 0},
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, DSI_ENABLE}, //DSI_ENABLE
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, DSI_ENABLE}, //DSI_ENABLE
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, 0},
{SleepOrRegisterWriteKind_Write, DC_DISP_DISP_WIN_OPTIONS, DSI_ENABLE}, //DSI_ENABLE
{SleepOrRegisterWriteKind_Write, DC_WIN_WIN_OPTIONS, WIN_ENABLE}, //Enable window AD.
{SleepOrRegisterWriteKind_Write, DC_CMD_DISPLAY_COMMAND, DISP_CTRL_MODE_C_DISPLAY}, //DISPLAY_CTRL_MODE: continuous display.
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_UPDATE | WIN_A_UPDATE}, //General update; window A update.
{SleepOrRegisterWriteKind_Write, DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ | WIN_A_ACT_REQ} //General activation request; window A activation request.
};
constexpr const RegisterWrite DisplayConfigDc01Fini01[] = {
{sizeof(u32) * DC_DISP_FRONT_PORCH, 0xA0088},
{sizeof(u32) * DC_CMD_INT_MASK, 0},
{sizeof(u32) * DC_CMD_STATE_ACCESS, 0},
{sizeof(u32) * DC_CMD_INT_ENABLE, 0},
{sizeof(u32) * DC_CMD_CONT_SYNCPT_VSYNC, 0},
{sizeof(u32) * DC_CMD_DISPLAY_COMMAND, DISP_CTRL_MODE_STOP},
{sizeof(u32) * DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{sizeof(u32) * DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
{sizeof(u32) * DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{sizeof(u32) * DC_CMD_GENERAL_INCR_SYNCPT, 0x301},
{sizeof(u32) * DC_CMD_GENERAL_INCR_SYNCPT, 0x301},
{sizeof(u32) * DC_CMD_STATE_CONTROL, GENERAL_UPDATE},
{sizeof(u32) * DC_CMD_STATE_CONTROL, GENERAL_ACT_REQ},
};
constexpr const RegisterWrite DisplayConfigDsi01Fini01[] = {
{sizeof(u32) * DSI_POWER_CONTROL, 0},
{sizeof(u32) * DSI_PAD_CONTROL_1, 0},
};
constexpr const RegisterWrite DisplayConfigDsi01Fini02[] = {
{sizeof(u32) * DSI_PHY_TIMING_1, 0x40A0E05},
{sizeof(u32) * DSI_PHY_TIMING_2, 0x30118},
{sizeof(u32) * DSI_BTA_TIMING, 0x190A14},
{sizeof(u32) * DSI_TIMEOUT_0, DSI_TIMEOUT_LRX(0x2000) | DSI_TIMEOUT_HTX(0xFFFF) },
{sizeof(u32) * DSI_TIMEOUT_1, DSI_TIMEOUT_PR(0x1343) | DSI_TIMEOUT_TA(0x2000)},
{sizeof(u32) * DSI_TO_TALLY, 0},
{sizeof(u32) * DSI_HOST_CONTROL, DSI_HOST_CONTROL_CRC_RESET | DSI_HOST_CONTROL_TX_TRIG_HOST | DSI_HOST_CONTROL_CS | DSI_HOST_CONTROL_ECC},
{sizeof(u32) * DSI_CONTROL, DSI_CONTROL_LANES(3) | DSI_CONTROL_HOST_ENABLE},
{sizeof(u32) * DSI_POWER_CONTROL, DSI_POWER_CONTROL_ENABLE},
{sizeof(u32) * DSI_MAX_THRESHOLD, 0x40},
{sizeof(u32) * DSI_TRIGGER, 0},
{sizeof(u32) * DSI_TX_CRC, 0},
{sizeof(u32) * DSI_INIT_SEQ_CONTROL, 0}
};
constexpr const SleepOrRegisterWrite DisplayConfigJdiSpecificFini01[] = {
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x439},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x9483FFB9},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2139},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x191919D5},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xB39},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x4F0F41B1},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xF179A433},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2D81},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x439},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xB9},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
};
constexpr const SleepOrRegisterWrite DisplayConfigAuoRev1SpecificFini01[] = {
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x439},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x9483FFB9},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2C39},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x191919D5},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x2C39},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x191919D6},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x19191919},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xB39},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x711148B1},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x71143209},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x114D31},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0x439},
{SleepOrRegisterWriteKind_Write, DSI_WR_DATA, 0xB9},
{SleepOrRegisterWriteKind_Write, DSI_TRIGGER, DSI_TRIGGER_HOST},
{SleepOrRegisterWriteKind_Sleep, 5, 0},
};
| 39,644
|
C++
|
.inc
| 642
| 57.239875
| 157
| 0.727119
|
Atmosphere-NX/Atmosphere
| 14,324
| 1,207
| 54
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,647
|
pdf.h
|
wkhtmltopdf_wkhtmltopdf/src/lib/pdf.h
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
* vi:set ts=4 sts=4 sw=4 noet :
*
* Copyright 2010-2020 wkhtmltopdf authors
*
* This file is part of wkhtmltopdf.
*
* wkhtmltopdf is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wkhtmltopdf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with wkhtmltopdf. If not, see <http: *www.gnu.org/licenses/>.
*/
#ifndef __PDF_H__
#define __PDF_H__
#ifdef BUILDING_WKHTMLTOX
#include "dllbegin.inc"
#else
#include <wkhtmltox/dllbegin.inc>
#endif
struct wkhtmltopdf_global_settings;
typedef struct wkhtmltopdf_global_settings wkhtmltopdf_global_settings;
struct wkhtmltopdf_object_settings;
typedef struct wkhtmltopdf_object_settings wkhtmltopdf_object_settings;
struct wkhtmltopdf_converter;
typedef struct wkhtmltopdf_converter wkhtmltopdf_converter;
typedef void (*wkhtmltopdf_str_callback)(wkhtmltopdf_converter * converter, const char * str);
typedef void (*wkhtmltopdf_int_callback)(wkhtmltopdf_converter * converter, const int val);
typedef void (*wkhtmltopdf_void_callback)(wkhtmltopdf_converter * converter);
CAPI(int) wkhtmltopdf_init(int use_graphics);
CAPI(int) wkhtmltopdf_deinit();
CAPI(int) wkhtmltopdf_extended_qt();
CAPI(const char *) wkhtmltopdf_version();
CAPI(wkhtmltopdf_global_settings *) wkhtmltopdf_create_global_settings();
CAPI(void) wkhtmltopdf_destroy_global_settings(wkhtmltopdf_global_settings *);
CAPI(wkhtmltopdf_object_settings *) wkhtmltopdf_create_object_settings();
CAPI(void) wkhtmltopdf_destroy_object_settings(wkhtmltopdf_object_settings *);
CAPI(int) wkhtmltopdf_set_global_setting(wkhtmltopdf_global_settings * settings, const char * name, const char * value);
CAPI(int) wkhtmltopdf_get_global_setting(wkhtmltopdf_global_settings * settings, const char * name, char * value, int vs);
CAPI(int) wkhtmltopdf_set_object_setting(wkhtmltopdf_object_settings * settings, const char * name, const char * value);
CAPI(int) wkhtmltopdf_get_object_setting(wkhtmltopdf_object_settings * settings, const char * name, char * value, int vs);
CAPI(wkhtmltopdf_converter *) wkhtmltopdf_create_converter(wkhtmltopdf_global_settings * settings);
CAPI(void) wkhtmltopdf_destroy_converter(wkhtmltopdf_converter * converter);
CAPI(void) wkhtmltopdf_set_debug_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_str_callback cb);
CAPI(void) wkhtmltopdf_set_info_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_str_callback cb);
CAPI(void) wkhtmltopdf_set_warning_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_str_callback cb);
CAPI(void) wkhtmltopdf_set_error_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_str_callback cb);
CAPI(void) wkhtmltopdf_set_phase_changed_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_void_callback cb);
CAPI(void) wkhtmltopdf_set_progress_changed_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_int_callback cb);
CAPI(void) wkhtmltopdf_set_finished_callback(wkhtmltopdf_converter * converter, wkhtmltopdf_int_callback cb);
/* CAPI(void) wkhtmltopdf_begin_conversion(wkhtmltopdf_converter * converter); */
/* CAPI(void) wkhtmltopdf_cancel(wkhtmltopdf_converter * converter); */
CAPI(int) wkhtmltopdf_convert(wkhtmltopdf_converter * converter);
CAPI(void) wkhtmltopdf_add_object(
wkhtmltopdf_converter * converter, wkhtmltopdf_object_settings * setting, const char * data);
CAPI(int) wkhtmltopdf_current_phase(wkhtmltopdf_converter * converter);
CAPI(int) wkhtmltopdf_phase_count(wkhtmltopdf_converter * converter);
CAPI(const char *) wkhtmltopdf_phase_description(wkhtmltopdf_converter * converter, int phase);
CAPI(const char *) wkhtmltopdf_progress_string(wkhtmltopdf_converter * converter);
CAPI(int) wkhtmltopdf_http_error_code(wkhtmltopdf_converter * converter);
CAPI(long) wkhtmltopdf_get_output(wkhtmltopdf_converter * converter, const unsigned char **);
#ifdef BUILDING_WKHTMLTOX
#include "dllend.inc"
#else
#include <wkhtmltox/dllend.inc>
#endif
#endif /*__PDF_H__*/
| 4,486
|
C++
|
.h
| 74
| 59.135135
| 128
| 0.798226
|
wkhtmltopdf/wkhtmltopdf
| 13,947
| 1,808
| 1,356
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,650
|
image.h
|
wkhtmltopdf_wkhtmltopdf/src/lib/image.h
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
* vi:set ts=4 sts=4 sw=4 noet :
*
* Copyright 2010-2020 wkhtmltopdf authors
*
* This file is part of wkhtmltopdf.
*
* wkhtmltopdf is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wkhtmltopdf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with wkhtmltopdf. If not, see <http: *www.gnu.org/licenses/>.
*/
#ifndef __IMAGE_H__
#define __IMAGE_H__
#ifdef BUILDING_WKHTMLTOX
#include "dllbegin.inc"
#else
#include <wkhtmltox/dllbegin.inc>
#endif
struct wkhtmltoimage_global_settings;
typedef struct wkhtmltoimage_global_settings wkhtmltoimage_global_settings;
struct wkhtmltoimage_converter;
typedef struct wkhtmltoimage_converter wkhtmltoimage_converter;
typedef void (*wkhtmltoimage_str_callback)(wkhtmltoimage_converter * converter, const char * str);
typedef void (*wkhtmltoimage_int_callback)(wkhtmltoimage_converter * converter, const int val);
typedef void (*wkhtmltoimage_void_callback)(wkhtmltoimage_converter * converter);
CAPI(int) wkhtmltoimage_init(int use_graphics);
CAPI(int) wkhtmltoimage_deinit();
CAPI(int) wkhtmltoimage_extended_qt();
CAPI(const char *)wkhtmltoimage_version();
CAPI(wkhtmltoimage_global_settings *) wkhtmltoimage_create_global_settings();
CAPI(int) wkhtmltoimage_set_global_setting(wkhtmltoimage_global_settings * settings, const char * name, const char * value);
CAPI(int) wkhtmltoimage_get_global_setting(wkhtmltoimage_global_settings * settings, const char * name, char * value, int vs);
CAPI(wkhtmltoimage_converter *) wkhtmltoimage_create_converter(wkhtmltoimage_global_settings * settings, const char * data);
CAPI(void) wkhtmltoimage_destroy_converter(wkhtmltoimage_converter * converter);
CAPI(void) wkhtmltoimage_set_debug_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_str_callback cb);
CAPI(void) wkhtmltoimage_set_info_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_str_callback cb);
CAPI(void) wkhtmltoimage_set_warning_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_str_callback cb);
CAPI(void) wkhtmltoimage_set_error_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_str_callback cb);
CAPI(void) wkhtmltoimage_set_phase_changed_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_void_callback cb);
CAPI(void) wkhtmltoimage_set_progress_changed_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_int_callback cb);
CAPI(void) wkhtmltoimage_set_finished_callback(wkhtmltoimage_converter * converter, wkhtmltoimage_int_callback cb);
CAPI(int) wkhtmltoimage_convert(wkhtmltoimage_converter * converter);
/* CAPI(void) wkhtmltoimage_begin_conversion(wkhtmltoimage_converter * converter); */
/* CAPI(void) wkhtmltoimage_cancel(wkhtmltoimage_converter * converter); */
CAPI(int) wkhtmltoimage_current_phase(wkhtmltoimage_converter * converter);
CAPI(int) wkhtmltoimage_phase_count(wkhtmltoimage_converter * converter);
CAPI(const char *) wkhtmltoimage_phase_description(wkhtmltoimage_converter * converter, int phase);
CAPI(const char *) wkhtmltoimage_progress_string(wkhtmltoimage_converter * converter);
CAPI(int) wkhtmltoimage_http_error_code(wkhtmltoimage_converter * converter);
CAPI(long) wkhtmltoimage_get_output(wkhtmltoimage_converter * converter, const unsigned char **);
#ifdef BUILDING_WKHTMLTOX
#include "dllend.inc"
#else
#include <wkhtmltox/dllend.inc>
#endif
#endif /*__IMAGE_H__*/
| 3,925
|
C++
|
.h
| 65
| 58.892308
| 128
| 0.802184
|
wkhtmltopdf/wkhtmltopdf
| 13,947
| 1,808
| 1,356
|
LGPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
9,738
|
square_free_number.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/square_free_number/square_free_number.cpp
|
//Program to check whether a number is square_free or not
#include <iostream>
#include <cmath>
bool isSquareFree(int n)
{
if (n % 2 == 0)
n /= 2;
if (n % 2 == 0)
return false;
for (int i = 3; i <= std::sqrt(n); i += 2)
if (n % i == 0)
{
n /= i;
if (n % i == 0)
return false;
}
return true;
}
int main()
{
int n;
std::cout << "Enter a number: ";
std::cin >> n;
if (isSquareFree(n))
std::cout << n << " is square free number";
else
std::cout << n << " is not a square free number";
return 0;
}
| 631
|
C++
|
.cpp
| 29
| 15.965517
| 57
| 0.477462
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,742
|
permutation_lexicographic_order.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/permutation_lexicographic_order/permutation_lexicographic_order.cpp
|
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
set<string> s;
void permutation(string a, int i = 0)
{
if (a[i] == '\0')
{
// cout << a << endl;
s.insert(a);
return;
}
for (int j = i; a[j] != '\0'; j++)
{
swap(a[i], a[j]);
permutation(a, i + 1);
swap(a[i], a[j]);
}
}
int main()
{
string a;
cout << "Enter any string : ";
cin >> a;
permutation(a);
set<string>::iterator i;
for (i = s.begin(); i != s.end(); i++)
cout << *i << endl;
return 0;
}
| 606
|
C++
|
.cpp
| 32
| 14.34375
| 42
| 0.486772
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,745
|
exponentiation_by_squaring.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
int power(int num, int exp)
{
if (exp == 0)
return 1;
if (exp == 1)
return num;
int temp = power(num, exp / 2);
temp *= temp;
if (exp % 2 == 1)
temp *= num;
return temp;
}
int main()
{
int num, exp;
cout << "Input Number and Its Exponent" << endl;;
cin >> num >> exp;
cout << power(num, exp) << endl;
}
| 450
|
C++
|
.cpp
| 22
| 16.545455
| 53
| 0.563084
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,755
|
gaussian_elimination.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/gaussian_elimination/gaussian_elimination.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
const long double EPS = 1e-8;
/**
* Gaussian elimination (also known as row reduction). Solves systems of linear equations.
*
* @param a is an input matrix
* @param ans is result vector
* @return number of system solutions (0 or 1), -1 if the system is inconsistent.
*/
int gauss(vector<vector <long double>> a, vector<long double> &ans)
{
int n = (int) a.size();
int m = (int) a[0].size() - 1;
vector<int> cged(m, -1);
ans.assign(m, 0);
for (int cur_col = 0, cur_row = 0; cur_col < m && cur_row < n; cur_col++)
{
int sel = cur_row;
for (int i = cur_row; i < n; i++)
if (abs(a[i][cur_col]) > abs(a[sel][cur_col]))
sel = i;
if (abs(a[sel][cur_col]) < EPS)
continue;
swap(a[sel], a[cur_row]);
cged[cur_col] = cur_row;
for (int i = 0; i < n; i++)
if (i != cur_row)
{
long double cf = -a[i][cur_col] / a[cur_row][cur_col];
for (int j = cur_col; j <= m; j++)
a[i][j] += a[cur_row][j] * cf;
}
cur_row++;
}
for (int i = 0; i < m; i++)
if (cged[i] != -1)
ans[i] = a[cged[i]][m] / a[cged[i]][i];
for (int i = 0; i < n; i++)
{
long double sum = 0.0;
for (int j = 0; j < m; j++)
sum += ans[j] * a[i][j];
if (abs(sum - a[i][m]) > EPS)
return 0;
}
for (int i = 0; i < m; i++)
if (cged[i] == -1)
return -1;
return 1;
}
/*
* Input:
* 2
* 2 1 4
* 1 2 5
* Output:
* single
* 1 2
*/
int main()
{
int n;
cin >> n;
vector <vector <long double>> l(n);
vector <long double> ans(n);
for (int i = 0; i < n; i++)
{
l[i].resize(n + 1);
for (int j = 0; j <= n; j++)
cin >> l[i][j];
}
int st = gauss(l, ans);
if (!(st + 1))
{
cout << "infinity\n";
return 0;
}
if (!st)
{
cout << "impossible\n";
return 0;
}
cout << "single\n";
for (int i = 0; i < n; i++)
cout << ans[i] << " ";
cout << "\n";
}
| 2,273
|
C++
|
.cpp
| 91
| 18.681319
| 91
| 0.455842
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,756
|
add_polynomials.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/add_polynomials/add_polynomials.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
/* Contributed by Vaibhav Jain (vaibhav29498) */
/* Refactored by Adeen Shukla (adeen-s) */
#include <iostream>
#include <stddef.h>
using namespace std;
struct term
{
int coeff;
int pow;
term* next;
term(int, int);
};
term::term(int c, int p)
{
coeff = c;
pow = p;
next = NULL;
}
class polynomial {
term* head;
public:
polynomial();
void insert_term(int, int);
void print();
friend polynomial operator+(polynomial, polynomial);
};
polynomial::polynomial()
{
head = NULL;
}
void polynomial::insert_term(int c, int p)
{
if (head == NULL)
{
head = new term(c, p);
return;
}
if (p > head->pow)
{
term* t = new term(c, p);
t->next = head;
head = t;
return;
}
term* cur = head;
while (cur != NULL)
{
if (cur->pow == p)
{
cur->coeff += c;
return;
}
if ((cur->next == NULL) || (cur->next->pow < p))
{
term* t = new term(c, p);
t->next = cur->next;
cur->next = t;
return;
}
cur = cur->next;
}
}
void polynomial::print()
{
term* t = head;
while (t != NULL)
{
cout << t->coeff;
if (t->pow)
cout << "x^" << t->pow;
if (t->next != NULL)
cout << "+";
t = t->next;
}
cout << endl;
}
polynomial operator+(polynomial p1, polynomial p2)
{
polynomial p;
term *t1 = p1.head, *t2 = p2.head;
while ((t1 != NULL) && (t2 != NULL))
{
if (t1->pow > t2->pow)
{
p.insert_term(t1->coeff, t1->pow);
t1 = t1->next;
}
else if (t1->pow < t2->pow)
{
p.insert_term(t2->coeff, t2->pow);
t2 = t2->next;
}
else
{
p.insert_term(t1->coeff + t2->coeff, t1->pow);
t1 = t1->next;
t2 = t2->next;
}
}
while (t1 != NULL)
{
p.insert_term(t1->coeff, t1->pow);
t1 = t1->next;
}
while (t2 != NULL)
{
p.insert_term(t2->coeff, t2->pow);
t2 = t2->next;
}
return p;
}
int main()
{
polynomial p1, p2;
p1.insert_term(7, 4);
p1.insert_term(4, 5);
p1.insert_term(10, 0);
p1.insert_term(9, 2);
cout << "First polynomial:";
p1.print();
p2.insert_term(5, 0);
p2.insert_term(6, 5);
p2.insert_term(7, 0);
p2.insert_term(3, 2);
cout << "Second polynomial:";
p2.print();
polynomial p3 = p1 + p2;
cout << "Sum:";
p3.print();
return 0;
}
| 2,673
|
C++
|
.cpp
| 132
| 14.272727
| 58
| 0.483017
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,759
|
horner_polynomial_evaluation.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/horner_polynomial_evaluation/horner_polynomial_evaluation.cpp
|
#include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
typedef long long ll;
typedef vector<ll> Poly;
// evaluate p(x) in linear time
ll evaluate(const Poly& p, ll x)
{
ll ret = 0;
for (int i = p.size() - 1; i >= 0; --i)
ret = ret * x + p[i];
return ret;
}
int main()
{
// polynomial degree
int n;
scanf("%d", &n);
Poly poly(n + 1);
// reads coefficients from lowest to highest power
for (int i = 0; i <= n; ++i)
scanf("%lld", &poly[i]);
// number of queries and x to evaluate
int q, x;
scanf("%d", &q);
while (q--)
{
scanf("%d", &x);
printf("%lld\n", evaluate(poly, x));
}
return 0;
}
| 735
|
C++
|
.cpp
| 33
| 18.151515
| 54
| 0.564029
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,766
|
fast_inverse_sqrt.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/fast_inverse_sqrt/fast_inverse_sqrt.cpp
|
// AUTHOR: Mitchell Haugen
// GITHUB: https://github.com/haugenmitch
// DATE: October 9, 2017
// SOURCE: https://stackoverflow.com/questions/1349542/john-carmacks-unusual-fast-inverse-square-root-quake-iii User: Rushyo
// DESCRIPTION: This algorithm use bit manipulation to calculate the inverse square root much faster than could be done if calculated in the proper way. It has surprising levels of accuracy that is sufficient for graphical applications.
#include <iostream>
#include <cstdint>
// Part of Cosmos by OpenGenus Foundation
double fastInverseSqrt(double x)
{
float xhalf = 0.5f * x;
std::int64_t i = *(std::int64_t*)&x; // get bits for double value
i = 0x5fe6eb50c7b537a9 - (i >> 1); // gives initial guess y0
x = *(double*)&i; // convert bits back to double
x = x * (1.5 - (xhalf * x * x)); // Newton step, repeating increases accuracy
return x;
}
int main()
{
double input;
std::cin >> input;
std::cout << fastInverseSqrt(input) << std::endl;
return 0;
}
| 1,074
|
C++
|
.cpp
| 24
| 41.875
| 236
| 0.672727
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,767
|
newman_conway_recursion.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/newman_conway/newman_conway_recursion.cpp
|
#include <iostream>
class NewmanConwaySequence
{
public:
NewmanConwaySequence(unsigned int n) : n(n) {}
unsigned int calculateNewmanConwaySequenceTermRecur(unsigned int n);
private:
unsigned int n;
};
unsigned int NewmanConwaySequence::calculateNewmanConwaySequenceTermRecur(unsigned int n)
{
if(n == 1 or n == 2)
return 1;
else
return calculateNewmanConwaySequenceTermRecur(calculateNewmanConwaySequenceTermRecur(n - 1)) + calculateNewmanConwaySequenceTermRecur(n - calculateNewmanConwaySequenceTermRecur(n - 1));
}
int main()
{
unsigned int nValue;
std::cout << "\nEnter the Index of Newman Conway Sequence : ";
std::cin >> nValue;
NewmanConwaySequence aNewmanConwaySequenceObj(nValue);
std::cout << "\nValue of term at " << nValue << " indexed in Newman Conway Sequence : " << aNewmanConwaySequenceObj.calculateNewmanConwaySequenceTermRecur(nValue);
}
| 921
|
C++
|
.cpp
| 24
| 34.625
| 193
| 0.76212
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,768
|
newman_conway_sequence.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/newman_conway/newman_conway_sequence.cpp
|
#include <iostream>
#include <vector>
//prints input number of teerms of Newman-Conway Sequence
std::vector<int> NewmanConwaySequence(int number)
{
std::vector<int> arr(number + 1);
arr[0] = 0;
arr[1] = 1;
arr[2] = 1;
for (int i = 3; i <= number; ++i)
arr[i] = arr[arr[i - 1]] + arr[i - arr[i - 1]];
return arr;
}
int main()
{
int number;
std::cout << "Enter number: ";
std::cin >> number;
std::vector<int> sequence(number + 1);
sequence = NewmanConwaySequence(number);
for (int i = 1; i <= number; ++i)
std::cout << sequence[i] << " ";
return 0;
}
| 618
|
C++
|
.cpp
| 24
| 21.875
| 57
| 0.581788
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,772
|
fibonacci_number.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.cpp
|
#include <iostream>
#include <vector>
/*
* Part of Cosmos by OpenGenus Foundation
* Don't use numbers bigger than (2^16)-1 as input for fib because some computers will crash due to memory issues.
*/
// Returns the nth term in the Fibonacci Sequence (dynamic): O(N) [nice performance]
unsigned long long bottom_up_fibonacci(unsigned short n)
{
std::vector<unsigned long long> f(n + 1);
f[0] = 0;
f[1] = 1;
for (int i = 2; i <= n; ++i)
f[i] = f[i - 1] + f[i - 2];
return f[n];
}
//Returns the nth term in the Fibonacci Sequence (recursive): O(2^N) [really slow]
unsigned long long recursive_fibonacci(unsigned short n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2);
}
int main()
{
unsigned short n = 45;
std::cout << "Calculating fib(" << n << ") using bottom-up method: ";
std::cout << bottom_up_fibonacci(n) << std::endl;
std::cout << "Calculating fib(" << n << ") using recursive method: ";
std::cout << recursive_fibonacci(n) << std::endl;
// As you can see bottom-up it's instantanious but recursive takes some seconds to calculate fib.
}
| 1,195
|
C++
|
.cpp
| 34
| 31.5
| 114
| 0.644714
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,774
|
convolution.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/convolution/convolution.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
// This code requires you to enable the C++11 standard when compiling
/**
* @breif convolve - compute the discrete time convolution of functions vectors f and g. Coded for clarity,
* not performance.
* @return f * g
**/
template <typename T>
std::vector<T> convolve(const std::vector<T>& f, const std::vector<T>& g)
{
if (f.size() < 1 || g.size() < 1)
return {};
const auto outputSize = static_cast<int>(f.size() + g.size() - 1);
std::vector<float> fg(outputSize, 0.0);
for (int n = 0; n < outputSize; n++)
for (int m = 0; m < static_cast<int>(g.size()); m++)
if (n - m >= 0 && n - m <= static_cast<int>(outputSize - g.size()))
fg[n] += f[n - m] * g[m];
return fg;
}
int main()
{
// In this example the input is a vector of 1s and the filter is a weighted
// average filter. The result is the sliding average of input using four points.
const auto input = std::vector<float>(5, 1.0f);
const auto filter = std::vector<float>(4, 0.25f);
const auto fg = convolve<float>(input, filter);
for (const auto& elem : fg)
std::cout << elem << std::endl;
return 0;
}
| 1,252
|
C++
|
.cpp
| 33
| 33.484848
| 107
| 0.61952
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,775
|
integer_to_roman.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/integer_to_roman/integer_to_roman.cpp
|
#include <iostream>
#include <string>
#include <map>
std::string integerToRoman(int number);
int main()
{
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "\nYour number: " << number << "\n";
std::cout << "Your number in Roman Numerals: " << integerToRoman(number) << "\n";
}
std::string integerToRoman(int number)
{
static std::map<int, std::string> romanNumerals
{
{1000, "M"},
{900, "CM"},
{500, "D"},
{400, "CD"},
{100, "C"},
{ 90, "XC"},
{ 50, "L"},
{ 40, "XL"},
{ 10, "X"},
{ 9, "IX"},
{ 5, "V"},
{ 4, "IV"},
{ 1, "I"}
};
std::string result;
for (auto it = romanNumerals.rbegin(); it != romanNumerals.rend(); ++it)
while (number >= it->first)
{
result += it->second;
number -= it->first;
}
return result;
}
| 946
|
C++
|
.cpp
| 39
| 18.025641
| 85
| 0.480534
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,776
|
pythagorean_triplet.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/pythagorean_triplet/pythagorean_triplet.cpp
|
// A Pythagorean triplet is a set of three natural numbers, a<b<c, for which a^2 + b^2 = c^2
// Given N, Check if there exists any Pythagorean triplet for which a+b+c=N
//Find maximum possible value of abc among all such Pythagorean triplets, If there is no such Pythagorean triplet print -1.
#include <iostream>
using namespace std;
#define opt std::ios_base::sync_with_stdio(false)
typedef long long int ll;
int main()
{
opt;
int t;
cin >> t;
while (t--)
{
double n;
ll m = 0;
cin >> n;
double a;
for (a = 1; a < n / 2; a++) // keeping a and n constant and using given two equations, we will get the value of b and c in terms of n and a
{ // from expression of b, we can see that a should be less than n/2
double b, c;
b = ((n * n) - 2 * a * n) / (2 * (n - a)); //solving the given 2 equations, we will get this expression of b
c = ((n - a) * (n - a) + (a * a)) / (2 * (n - a)); //solving the given 2 equations, we will get this expression of c
int p = int(b), q = int(c);
if (b == p && c == q && ((a * a + b * b) == (c * c)) )
m = max(m, ll(ll(a) * p * q));
}
(m != 0) ? cout << m << endl : cout << -1 << endl;
}
}
| 1,321
|
C++
|
.cpp
| 30
| 37.466667
| 150
| 0.52795
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,786
|
newton_raphson.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/newton_raphson_method/newton_raphson.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <cmath>
#include <iostream>
#include <limits>
#include <string>
#include <stdexcept>
// This code requires you to enable the C++11 standard when compiling
void helpAndExit()
{
std::cout << "Newton-Raphson iteration for the function x*log10(x)-1.2\n"
<< "\nUsage: newton-raphson INITIAL_GUESS ERROR_LIMIT MAX_ITERATIONS\n"
<< "\tINITIAL_GUESS - The initial guess (x0). A number.\n"
<< "\tERROR_LIMIT - The stopping condition. A positive number.\n"
<< "\tMAX_ITERATIONS - The maximum number of allowed iterations. A positive number.\n"
<< "\n\tExample: newton_raphson 1 0.001 1000" << std::endl;
exit(1);
}
int main(int argc, char* argv[])
{
if (argc != 4)
helpAndExit();
float x0, allowedError;
int maxIterations;
try {
x0 = std::stof(std::string(argv[1]));
allowedError = std::stof(std::string(argv[2]));
maxIterations = std::stoi(std::string(argv[3]));
if (allowedError < 0.0f || maxIterations < 0)
throw std::domain_error("Error limit and number of iterations must be positive numbers!");
} catch (std::exception& e)
{
std::cout << e.what() << "\n" << std::endl;
helpAndExit();
}
auto f = [](const float x)
{
return x * std::log10(x) - 1.2;
};
auto df = [](const float x)
{
return std::log10(x) + 0.43429;
};
for (auto i = 1; i < maxIterations; i++)
{
const auto error = f(x0) / df(x0);
if (std::fabs(error) < allowedError)
{
std::cout << "Conversion reached after: " << i << " iterations. Solution: " << x0 <<
std::endl;
return 0;
}
x0 = x0 - error;
}
std::cout << "Convergence not reached after " << maxIterations << " iterations" << std::endl;
return 0;
}
| 1,999
|
C++
|
.cpp
| 56
| 27.839286
| 102
| 0.558031
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,789
|
spiral_matrix_clockwise_cycle.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/spiral_matrix/spiral_matrix_clockwise_cycle.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
using namespace std;
void print_top_row(int x, int y, int X, int Y, vector<vector<int>>matrix) {
for (int i = y; i<= Y; ++i) cout<<matrix[x][i]<<" ";
}
void print_right_column(int x, int y, int X, int Y, vector<vector<int>>matrix) {
for(int i = x; i<= X; ++i) cout<<matrix[i][Y]<<" ";
}
void print_bottom_row(int x, int y, int X, int Y, vector<vector<int>>matrix) {
for(int i = Y; i>= y; --i) cout<<matrix[X][i]<<" ";
}
void print_left_column(int x, int y, int X, int Y, vector<vector<int>>matrix) {
for(int i = X; i >= x; --i) cout<<matrix[i][y]<<" ";
}
void cartisian_cycle(vector<vector<int>>matrix) {
int x = 0, y = 0;
int X = matrix.size() - 1;
int Y = matrix[0].size() - 1;
while (true)
{
if (x > X || y > Y) break;
print_top_row(x, y, X, Y, matrix); ++x;
if (x > X || y > Y) break;
print_right_column(x, y, X, Y, matrix); --Y;
if (x > X || y > Y) break;
print_bottom_row(x, y, X, Y, matrix); --X;
if (x > X || y > Y) break;
print_left_column(x, y, X, Y, matrix); ++y;
}
}
/* Driver Code */
int main()
{
vector<vector<int>> a = { { 1, 2, 3, 4 },
{ 12, 13, 14, 5 },
{ 11, 16, 15, 6 },
{ 10, 9, 8, 7 } };
cartisian_cycle(a);
vector<vector<int>> b = { {1,2,3},
{12,13,4},
{11,14,5},
{10,15,6},
{9,8,7} };
cartisian_cycle(b);
return 0;
}
| 1,688
|
C++
|
.cpp
| 50
| 25.5
| 80
| 0.472292
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,790
|
recursive_spiral_matrix.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/spiral_matrix/recursive_spiral_matrix.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
using namespace std;
/*
This algorithm takes in a 2-dimensional vector and
outputs its contents in a clockwise spiral form.
Example Input:
[ [ 1 2 3 4 ],
[ 5 6 7 8 ],
[ 9 10 11 12 ],
[ 13 14 15 16 ] ];
Example Traversal:
1 → 2 → 3 → 4
↓
5 → 6 → 7 8
↑ ↓ ↓
9 10 ← 11 12
↑ ↓
13 ← 14 ← 15 ← 16
Example Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
*/
// Recursive implementation of printing a matrix in clockwise spiral form
// Informally, this function prints the outermost "ring" around the matrix,
// in a clockwise fashion, and then prints the next outermost "ring", and so on
// Arguments:
// mat: a 2-dimensional vector of ints
//
// row_start/col_start: beginning index of matrix (i.e. 0, 0)
//
// row_end/col_end: ending index of matrix (a 0-based index!)
// Ex. a 4 x 4 matrix would have an ending index of 3, 3
// a 5 x 6 matrix would have an ending index of 4, 5
// Time Complexity: O(m*n)
// Space Complexity: O(1), 2-d vector is passed by reference
void spiral_print(vector<vector<int> > &mat, int row_start, int col_start,
int row_end, int col_end) {
// check to see if we are "outside" the ring we are currently printing
if (row_start > row_end || col_start > col_end) {
return;
}
// Print top row
for (int i = row_start; i <= col_end; i++) {
cout << mat[row_start][i] << " ";
}
// Print rightmost column
for (int i = row_start + 1; i <= row_end; i++) {
cout << mat[i][col_end ] << " ";
}
// Print bottom row, only if this row hasn't been printed yet
if (row_end != row_start) {
for (int i = col_end - 1; i >= col_start; i--) {
cout << mat[row_end][i] << " ";
}
}
// Print leftmost column, only if this column hasn't been printed yet
if (col_end != col_start) {
for (int i = row_end - 1; i > row_start; i--) {
cout << mat[i][col_start] << " ";
}
}
// Function calls itself to print the next innermost "ring"
spiral_print(mat, row_start + 1, col_start + 1, row_end - 1, col_end - 1);
}
// Driver
int main()
{
// a 4x4 matrix
vector<vector<int> > mat_a = { {1, 2, 3, 4},
{ 12, 13, 14, 5},
{ 11, 16, 15, 6},
{ 10, 9, 8, 7} };
spiral_print(mat_a, 0, 0, 3, 3);
cout << '\n';
// a 3x10 matrix
vector<vector<int> > mat_b = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{21, 22, 23, 24, 25, 26, 27, 28, 29, 10},
{20, 19, 18, 17, 16, 15, 14, 13, 12, 11}};
spiral_print(mat_b, 0, 0, 2, 9);
cout << '\n';
// a 12x4 matrix
vector<vector<int> > mat_c = { {1, 2, 3, 4},
{28, 29, 30, 5},
{27, 48, 31, 6},
{26, 47, 32, 7},
{25, 46, 33, 8},
{24, 45, 34, 9},
{23, 44, 35, 10},
{22, 43, 36, 11},
{21, 42, 37, 12},
{20, 41, 38, 13},
{19, 40, 39, 14},
{18, 17, 16, 15}};
spiral_print(mat_c, 0, 0, 11, 3);
cout << '\n';
}
| 3,751
|
C++
|
.cpp
| 97
| 28.082474
| 79
| 0.447931
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,791
|
method2_power_recursion_with_even_odd_optimization.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/power/method2_power_recursion_with_even_odd_optimization.cpp
|
#include<bits/stdc++.h>
using namespace std;
// O(log2(p))
int power(int base,int p,int mod){
if(p==0)
return 1;
else if(p%2==0)
return power( ((base %mod)*(base %mod)) %mod, p/2, mod);
else if(p%2==1)
return ( (base%mod) * (power(((base %mod)*(base %mod))%mod, p/2, mod) %mod)) %mod;
}
int main(){
int base,p,mod;
while(cin>>base>>p>>mod){
cout<< power(base,p,mod) <<"\n";
}
return 0;
}
| 458
|
C++
|
.cpp
| 18
| 20.555556
| 90
| 0.537209
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,792
|
method1_power_recursion_with_even_odd_optimization.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/power/method1_power_recursion_with_even_odd_optimization.cpp
|
#include<bits/stdc++.h>
using namespace std;
// O(log2(p))
long long power(int base,int p){
if(p==0)
return 1;
else if(p%2==0)
return power(base*base,p/2);
else if(p%2==1)
return base*power(base*base,p/2);
}
int main(){
int base,p;
while(cin>>base>>p){
cout<< power(base,p) <<"\n";
}
return 0;
}
| 364
|
C++
|
.cpp
| 18
| 15.444444
| 41
| 0.556213
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,797
|
matrix_row_reduction.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/matrix_row_reduction/matrix_row_reduction.cpp
|
#include<iostream>
#include<string>
#include<vector>
#include<set>
using namespace std;
void PrintMatrix(vector<vector<float>>& matrix); //Prints matrix to console
int FirstNonZero(vector<float>& vec); //find first non-zero coefficient in a given row, returns -1 if unfound
void RowReduction(vector<vector<float>>& matrix) {
//Reduces a matrix to it's reduced row echelon form
int iteration = 0;
while (iteration != matrix[0].size() - 1) {
for (int i = iteration; i < matrix.size(); i++) {
float divisor = 1;
int pivot = FirstNonZero(matrix[i]);
if (pivot != -1)
divisor = matrix.at(i).at(pivot);
for (int j = 0; j < matrix[i].size(); j++)
if (pivot != -1)
matrix[i][j] /= divisor;
}
for (int i = iteration + 1; i < matrix.size(); i++) {
int pivot = FirstNonZero(matrix[iteration]);
if (pivot != -1 && matrix[i][pivot] != 0) {
for (int j = pivot; j < matrix.at(i).size(); j++) {
matrix[i][j] -= matrix[iteration][j];
}
}
}
iteration++;
}
//correct the row order
for (int i = 0; i < matrix.size(); i++) {
int index = FirstNonZero(matrix.at(i));
if (index == -1) {
continue;
}
vector<float> temp = matrix[index];
matrix[index] = matrix.at(i);
matrix[i] = temp;
}
cout << "Row Echelon Form:" << endl;
PrintMatrix(matrix);
cout << endl;
//test if system is consistent
set<int> pivots;
for (vector<float> row : matrix) {
if (FirstNonZero(row) == -1) {
if (row.back() != 0) {
cout << "The System of Equations has No Solution" << endl;
return;
}
}
else
pivots.insert(FirstNonZero(row));
}
unsigned int freeVar = matrix[0].size() - 1 - pivots.size();
if (freeVar == 0)
cout << "The System of Equations has one Solution" << endl;
else
cout << "The System of Equations has many Solutions" << endl;
cout << "The System has " << freeVar << " free variable(s).\n" << endl;
iteration = matrix.size() - 1;
//Reduces the matrix to its reduced echelon form
while (iteration > 0) {
for (int i = 0; i < iteration; i++) {
int pivot = FirstNonZero(matrix[iteration]);
float multiple = 0;
if (pivot != -1)
multiple = matrix.at(i).at(pivot);
for (int j = 0; j < matrix.at(i).size(); j++) {
matrix[i][j] -= (matrix[iteration][j] * multiple);
}
}
iteration--;
}
cout << "Reduced Echelon From:" << endl;
PrintMatrix(matrix);
if (freeVar == 0) { //Case 1 there is a single solution
vector<float> solutions;
solutions.resize(matrix[0].size() - 1);
for (vector<float> row : matrix) {
if (FirstNonZero(row) == -1)
continue;
float val = round(row.back() * 100.0) / 100.0;
if (val == -0)
val = 0;
solutions.at(FirstNonZero(row)) = val;
}
cout << "\nThe solution to this set of Equations is (";
for (float val : solutions) {
if (val == solutions.back())
cout << val << ")\n";
else
cout << val << ", ";
}
}
else { //Case 2 there are infinite solutions
vector<string> equations;
equations.resize(matrix[0].size() - 1);
for (vector<float> row : matrix) {
int index = FirstNonZero(row);
if (index == -1)
continue;
string equation = "";
for (int i = index + 1; i < row.size(); i++) {
float value = round(row[i] * 100.0) / 100.0;
if (value != 0 && value != -0) {
float absVal = abs(value);
string temp = to_string(absVal);
if (i == row.size() - 1) {
if (equation == "") {
if (value < 0)
equation.append("-");
}
else {
if (value > 0)
equation.append(" + ");
else
equation.append(" - ");
}
equation.append(temp.substr(0, temp.find_first_of('.') + 3));
}
else {
if (equation == "") {
if (value > 0)
equation.append("-");
}
else {
if (value < 0)
equation.append(" + ");
else
equation.append(" - ");
}
equation.append(temp.substr(0, temp.find_first_of('.') + 3) + "X" + to_string(i + 1));
}
}
}
equations[index] = equation;
}
cout << "\nThe solution set to this set of Equations is (";
for (int i = 0; i < equations.size(); i++) {
if (equations.at(i) == "")
equations.at(i) = "X" + to_string(i + 1);
if (i == equations.size() - 1)
cout << equations.at(i) << ")\n";
else
cout << equations.at(i) << ", ";
}
}
}
//Prints Matrix
void PrintMatrix(vector<vector<float>>& matrix) {
for (vector<float> row : matrix) {
for (float value : row) {
if (value == -0)
cout << "0 ";
else
cout << value << " ";
}
cout << endl;
}
}
//Find the index of the first non zero value in a row returns -1 if all but the last value are zero
int FirstNonZero(vector<float>& vec) {
for (int i = 0; i < vec.size() - 1; i++) {
if (vec.at(i) != 0 && vec.at(i) != -0)
return i;
}
return -1;
}
void main() {
//This is just the input for the matrix to solve the system of equations, just an example so you can use the algorithm
cout << "Please insert the coefficients of each equation separated by semicolons (A;B;C:...:N;b)\nEquations should be in the form Ax + By + Cz + ... + Nn = b. Separate each equation with a new line." << endl << "Type 'solve' when finished" << endl;
string input = "";
string delimiter = ";";
size_t pos = 0;
vector<vector<float>> matrix;
int row = 0;
int columnSize = 0;
while (1) {
int currColumnSize = 0;
vector<float> tempVec;
getline(cin, input);
if (input == "solve")
break;
while ((pos = input.find(delimiter)) != std::string::npos) {
if (input.substr(0, pos).find_first_not_of("0123456789-") != std::string::npos) {
cout << "Error: Invalid Coefficient\n\nCoefficient is not an integer" << endl;
return;
}
int temp = stoi(input.substr(0, pos));
tempVec.push_back(temp);;
input.erase(0, pos + delimiter.length());
currColumnSize++;
}
int temp = stoi(input);
tempVec.push_back(temp);
currColumnSize++;
if (currColumnSize != columnSize && columnSize != 0) {
cout << "Error: Invalid Formating" << endl << endl << "All Rows do not have the same number of columns.\nIf an equation is missing a variable there should be a coefficient of 0 to fill its place." << endl;
return;
}
columnSize = currColumnSize;
matrix.push_back(tempVec);
row++;
}
cout << "\nMatrix you entered:" << endl;
PrintMatrix(matrix);
cout << endl;
//This is where the actual algorithm starts
RowReduction(matrix);
}
| 6,644
|
C++
|
.cpp
| 212
| 26.523585
| 250
| 0.587867
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,799
|
decimal_to_bin.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/integer_conversion/decimal_to_bin.cpp
|
#include <iostream>
using namespace std;
int main()
{
int decimal;
cout << "Enter a decimal: ";
cin >> decimal;
cout << "The number in binary: ";
for (int i = 31; i >= 0; i--)
cout << ((decimal >> i) & 1);
cout << endl;
return 0;
}
| 271
|
C++
|
.cpp
| 13
| 16.846154
| 37
| 0.537255
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,801
|
next_larger_number.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/next_larger_number/next_larger_number.cpp
|
#include <iostream>
#include <algorithm>
#include <cstring>
// Part of Cosmos by OpenGenus Foundation
void nextgr(char num[], int n)
{
int i, j;
for (i = n - 1; i >= 0; --i)
if (num[i - 1] < num[i])
break;
if (i == 0)
{
std::cout << "No such greater number exists";
return;
}
int x = num[i - 1], small = i;
for (j = i + 1; j < n; ++j)
if (num[j] > x && num[j] < num[small])
small = j;
std::swap(num[i - 1], num[small]);
std::sort(num + i, num + n);
std::cout << num;
}
int main()
{
using namespace std;
char num[20];
cin >> num;
int n = strlen(num);
nextgr(num, n);
cout << endl;
return 0;
}
| 727
|
C++
|
.cpp
| 33
| 16.939394
| 53
| 0.500732
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,802
|
2sum.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/2sum/2sum.cpp
|
//Given an array and a sum, print two numbers from the array that add-up to sum
#include <iostream>
#include <map>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
#define ll long long
map<ll, ll> m;
//Function to find two numbers which add up to sum
void twoSum(ll a[], ll sum, int n)
{
for (int i = 0; i < n; i++)
if (m[sum - a[i]])
{
cout << "The two numbers are ";
cout << a[i] << " " << sum - a[i] << endl;
return;
}
}
int main()
{
ll a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(ll);
ll sum = 8;
for (int i = 0; i < n; i++)
m[a[i]] = 1;
twoSum(a, sum, n);
return 0;
}
| 693
|
C++
|
.cpp
| 28
| 20.178571
| 79
| 0.534039
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,803
|
simpsons_rule.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/simpsons_rule/simpsons_rule.cpp
|
#include <iostream>
#include <cmath>
float create(int x)
{
return log(x);
}
int simpson(int x1, int x2)
{
float h = (x2 - x1) / 6;
int x[10];
float y[10];
for (int i = 0; i <= n; ++i) {
x[i] = x1 + i * h;
y[i] = create(x[i]);
}
float value = 0;
for (int i = 0; i <= n; ++i) {
if (i == 0 || i == n)
value += y[i];
else if (i % 2 != 0)
value += 4 * y[i];
else
value += 2 * y[i];
}
value *= h / 3;
return value;
}
int main()
{
cout << "Enter the lower limit";
cin >> x1;
cout << "Enter the upper limit";
cin >> x2;
cout << simpson(x1, x2)<< "\n";
}
| 690
|
C++
|
.cpp
| 35
| 14.6
| 36
| 0.434716
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,804
|
steepest_descent.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/steepest_descent/steepest_descent.cpp
|
/*
* The method of steepest descent
* -------------------
* An algorithm for finding the nearest local minimum of a function.
* It solves an equation in quadratic form: Ax = b where x is the values we seek.
* A is a matrix of size NxN, and b is a vector of N values.
*
* Time complexity
* ---------------
* O(e^-2), where e is an error we can accept (indicates how far we are from solution).
*
* Space complexity
* ----------------
* O(2*N), where N is a size of matrix
*/
#include <iostream>
#include <array>
#include <cmath>
/*
* Evalutates euclidean norm
*/
template <long unsigned int S>
double norm(const std::array<double, S> &x, const std::array<double, S> &y)
{
double result = 0;
for (unsigned int i = 0; i < S; ++i)
result += (x[i] - y[i]) * (x[i] - y[i]);
return std::move(sqrt(result));
}
/*
* Adds up two matrix
*/
template <long unsigned int S>
std::array<double, S> operator+(const std::array<double, S> &x, const std::array<double, S> &y)
{
std::array<double, S> result;
for (unsigned int i = 0; i < S; ++i)
result[i] = x[i] + y[i];
return std::move(result);
}
/*
* Subtrack two matrix
*/
template <long unsigned int S>
std::array<double, S> operator-(const std::array<double, S> &x, const std::array<double, S> &y)
{
std::array<double, S> result;
for (unsigned int i = 0; i < S; ++i)
result[i] = x[i] - y[i];
return std::move(result);
}
/*
* Multiplication of matrix and constant value
*/
template <long unsigned int S>
std::array<double, S> operator*(const double x, const std::array<double, S> &y)
{
std::array<double, S> result;
for (unsigned int i = 0; i < S; ++i)
result[i] = x * y[i];
return std::move(result);
}
/*
* Multiplication of NxN and Nx1 matrix
*/
template <long unsigned int S>
std::array<double, S> operator*(const std::array<std::array<double, S>, S> &A,
const std::array<double, S> &b)
{
std::array<double, S> result = {0.0};
for (unsigned int i = 0; i < S; ++i)
for (unsigned int j = 0; j < S; ++j)
result[i] += A[i][j] * b[j];
return result;
}
/*
* Method of Steepest Descent
*/
template <long unsigned int S>
std::array<double, S> steepestdescent(const std::array<std::array<double, S>, S> &A,
const std::array<double, S> &b,
const double e = 0.0001, const double step = 0.1,
const unsigned int IterMax = 10000)
{
std::array<double, S> x = {0.0};
unsigned int k = 0;
do
{
std::array<double, S> xp = x;
std::array<double, S> residual = b - A * xp;
x = x + step * residual;
if (norm(x, xp) < e)
break;
k += 1;
}
while (k < IterMax);
return std::move(x);
}
/*
* Overloads operator << to display NxN size array
*/
template <long unsigned int S>
std::ostream &operator<<(std::ostream &stream, const std::array<std::array<double, S>, S> &A)
{
for (std::array<double, S> tmp : A)
{
for (double i : tmp)
stream << i << '\t';
stream << '\n';
}
return stream;
}
/*
* Overloads operator << to display Nx1 size array
*/
template <long unsigned int S>
std::ostream &operator<<(std::ostream &stream, const std::array<double, S> &x)
{
for (double i : x)
stream << i << '\n';
return stream;
}
int main()
{
const long unsigned int S = 3;
const std::array<std::array<double, S>, S> A = {1, -1, 1, 1, 1, 0, 1, 2, 0};
const std::array<double, S> b = {9, 1, -2};
std::array<double, S> x;
std::array<double, S> tmp;
// std::cout << "Maxtrix A:\n"<< A << '\n';
std::cout << "Vector b:\n" << b << '\n';
x = steepestdescent(A, b, 0.0000001);
std::cout << "Result:\n" << x << '\n';
tmp = A * x;
std::cout << "Ax = :\n" << tmp << '\n';
return 0;
}
| 3,957
|
C++
|
.cpp
| 137
| 24.262774
| 95
| 0.563947
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,806
|
sum_of_primes.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/prime_factors/sum_of_primes.cpp
|
// A C++ program to find the sum of all the primes not greater than given N.
// Constraints: 1<=N<=10^6
// Constraints : 1<=t<=10^6
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
typedef long long int ll;
using namespace std;
int a[1000005] = {0}; ll b[1000005] = {0};
void sieve(int n)
{
ll s = 0;
int i;
for (i = 2; i * i <= n; i++)
{
if (a[i] == 0)
{
s += i;
for (int j = 2 * i; j <= n; j += i)
a[j] = 1;
}
b[i] = s;
}
int j;
for (j = i; j <= n; j++)
{
if (a[j] == 0)
s += j;
b[j] = s;
}
}
int main()
{
sieve(1000000); // precomputing the summation of all primes upto n less than or equal to 10^6
int t;
cin >> t; // No. of test cases as input
while (t--)
{
int n;
cin >> n; // Given input number n
cout << b[n] << endl; // b[n] gives summation of all primes less than or equal to n.
}
}
| 996
|
C++
|
.cpp
| 42
| 18.261905
| 97
| 0.490011
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,809
|
gcd_and_lcm.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/gcd_and_lcm/gcd_and_lcm.cpp
|
#include <stdio.h>
#include <algorithm>
// Part of Cosmos by OpenGenus Foundation
int gcd(int x, int y)
{
while (y > 0)
{
x %= y;
std::swap(x, y);
}
return x;
}
//should use this recursive approach.
// int gcd(int c,int d)
// {
// if(d==0)
// return a;
// return gcd(d,c%d);
// }
int lcm(int x, int y)
{
return x / gcd(x, y) * y;
}
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("GCD = %d\n", gcd(a, b));
printf("LCM = %d", lcm(a, b));
}
| 516
|
C++
|
.cpp
| 30
| 14.366667
| 41
| 0.511387
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,810
|
replace_0_with_5.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
int main()
{
int n; cin >> n;
int a = 1;
while (n / a >= 1)
{
a = a * 10;
int temp = n % a - n % (a / 10);
temp = temp / (a / 10);
int temp2;
if (temp == 0)
{
temp2 = 5 * (a / 10);
n = n - temp + temp2;
}
}
cout << n << endl;
}
| 428
|
C++
|
.cpp
| 21
| 13.809524
| 41
| 0.418782
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,813
|
Binary_GCD_Recursive.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/Binary_GCD_Algorithm/Binary_GCD_Recursive.cpp
|
// Recursive program
#include <bits/stdc++.h>
using namespace std;
// Function to implement the
// Stein's Algorithm
int gcd(int x, int y)
{
if (x == y)
return x;
if (x == 0)
return y;
if (y == 0)
return x;
// look for factors of 2
if (~x & 1) // x is even
{
if (y & 1) // y is odd
return gcd(x >> 1, y);
else // both x and y are even
return gcd(x >> 1, y >> 1) << 1;
}
if (~y & 1) // x is odd, y is even
return gcd(x, y >> 1);
// reduce larger number
if (x > y)
return gcd((x - y) >> 1, y);
return gcd((y - x) >> 1, x);
}
// Driver code
int main()
{
int a = 34, b = 17;
cout<<"Gcd of given numbers is"<<gcd(a, b));
return 0;
}
| 695
|
C++
|
.cpp
| 35
| 17.085714
| 45
| 0.543645
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,814
|
Binary_GCD_Iterative.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/Binary_GCD_Algorithm/Binary_GCD_Iterative.cpp
|
// Iterative Approach
#include <bits/stdc++.h>
using namespace std;
//GCD Function
int gcd(int x, int y)
{
if (x == 0)
return y;
if (y == 0)
return x;
/*Finding K, where K is the
greatest power of 2
that divides both a and b. */
int k;
for (k = 0; ((x | y) && 1) == 0; ++k)
{
x >>= 1;
y >>= 1;
}
/* Dividing x by 2 until x becomes odd */
while ((x > 1) == 0)
x >>= 1;
/* From here on, 'x' is always odd. */
do {
/* If y is even, remove all factor of 2 in y */
while ((y > 1) == 0)
y >>= 1;
// Now x and y are both odd
if (x > y)
swap(x, y); // Swap u and v.
x = (y - a);
} while (y != 0);
return x << k;
}
// Driver code
int main()
{
int x = 72, b = 12;
cout<<"Gcd of given numbers is "<< gcd(x, y));
return 0;
}
| 776
|
C++
|
.cpp
| 41
| 16.390244
| 48
| 0.535912
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,816
|
coprime_numbers.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.cpp
|
#include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
template<typename int_type>
int_type gcd(int_type i, int_type j)
{
while (j != 0)
{
int_type x = i;
i = j;
j = x % j;
}
return i;
}
template<typename int_type>
bool isCoPrime(int_type i, int_type j)
{
return gcd<int_type>(i, j) == 1;
}
int main()
{
long long i, j;
cout << "Enter two numbers : ";
scanf("%lld %lld", &i, &j);
cout << isCoPrime(i, j) << endl;
return 0;
}
| 520
|
C++
|
.cpp
| 27
| 15.777778
| 41
| 0.587755
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,817
|
lexicographic_string_rank.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/lexicographic_string_rank/lexicographic_string_rank.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
/* Lexicographic String Rank */
/* O(n) time algorithm */
#include <iostream>
#include <string.h>
using namespace std;
typedef long long ll;
void factorial(ll fact[], int n)
{
fact[0] = 1;
for (int i = 1; i <= n; i++)
fact[i] = fact[i - 1] * i;
}
void initialize_char_cnt(int char_count[], string s, int len)
{
for (int i = 0; i < 256; i++)
char_count[i] = 0;
for (int i = 0; i < len; i++)
char_count[s[i] - char(0)]++;
}
void initialize_smaller_char_cnt(int smaller_char_count[], int char_count[])
{
smaller_char_count[0] = 0;
for (int i = 1; i < 256; i++)
smaller_char_count[i] = smaller_char_count[i - 1] + char_count[i - 1];
}
void update_char_count(int char_count[], char c)
{
--char_count[c - char(0)];
}
void update_smaller_char_count(int smaller_char_count[], char c)
{
for (int i = c + 1; i < 256; i++)
smaller_char_count[i]--;
}
ll lexicographic_string_rank(string s)
{
int len = s.length();
int char_count[256], smaller_char_count[256];
ll fact[len + 1], rep_count = 1, lex_string_rank = 0;
factorial(fact, len); //////////// Pre-computation of Factorial is needed for avoiding computing them in future again and again
initialize_char_cnt(char_count, s, len); //////////// Initialize char_count array
initialize_smaller_char_cnt(smaller_char_count, char_count); //////////// Initialize smaller_char_count array
for (int i = 0; i < 256; i++)
rep_count *= fact[char_count[i]]; //////////// Repetitive characters will cause duplicate permutations hence rank is divided by rep_count!
for (int i = 0; i < len; i++)
{
lex_string_rank += (fact[len - i - 1] * (smaller_char_count[s[i] - char(0)]) / rep_count);
rep_count = rep_count / char_count[s[i] - char(0)];
update_char_count(char_count, s[i]); //////////// Current character no longer needed as its position is fixed now
update_smaller_char_count(smaller_char_count, s[i]);
}
return lex_string_rank;
}
int main()
{
string s = "software";
cin >> s;
ll lex_string_rank = lexicographic_string_rank(s);
cout << "Lexicographic String Rank is: " << lex_string_rank << endl;
return 0;
}
| 2,280
|
C++
|
.cpp
| 62
| 32.903226
| 149
| 0.613718
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,819
|
std.cpp
|
OpenGenus_cosmos/code/mathematical_algorithms/src/std/std.cpp
|
#include <cmath>
template <typename T>
typename T::value_type mean(const T& container)
{
typename T::value_type result;
for (const auto& value : container)
result += value;
if (container.size() > 0)
result /= container.size();
return result;
}
template <typename T>
typename T::value_type var(const T& container)
{
auto mu = mean(container);
typename T::value_type result;
for (const auto& value : container)
{
auto res = value - mu;
result += res * res;
}
if (container.size() > 1)
result /= container.size() - 1;
return result;
}
template <typename T>
typename T::value_type stdDev(const T& container)
{
return std::sqrt(var(container));
}
| 734
|
C++
|
.cpp
| 30
| 20.4
| 49
| 0.644286
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,820
|
Iteration Method.cpp
|
OpenGenus_cosmos/code/numerical_analysis/iteration/src/Iteration Method.cpp
|
#include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation x*x*x+x-5=0 by Iteration Method
By simplified this equation we got eq=pow(5-x,(1/3)) then differentiate eq we got (-1/3*pow(5-x,(2/3)))
then we checked if we put natural number in x, will it lower than 1 for all natural number? if no we can't
apply iteration method else we can apply iteration method
*/
int main()
{
float x=1;
float eq=pow(5-x,(1/3));
float diff=(-1/3*pow(5-x,(2/3)));
int flag=0;
cout<<" Here us The Equation : \n";
cout<<" x*x*x+x-5=0 \n\n\n";
while(x<100)
{
if((-1/3*pow(5-x,(2/3)))>1)
{
flag=1;
break;
}
x++;
}
if(flag==1)
{
cout<<"Iteration Method Not Applicable in This Equation\n";
}
else
{
x=1;
for(int i=1;i<=10;i++)
{
x=sqrt(1/x+1);
cout<<"Step Taken "<<i<<" X="<<x<<endl;
}
}
return 0;
}
| 1,004
|
C++
|
.cpp
| 40
| 19.1
| 109
| 0.536458
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,821
|
Newton Rapson Method.cpp
|
OpenGenus_cosmos/code/numerical_analysis/newton_rapson/src/Newton Rapson Method.cpp
|
#include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation x*x*x-18=0 by Newton Rapson Method
First we take 2 values from function of the Equation (negative/positive) then place it in x and y
then we Differentiate This equation;
then apply formula
*/
double func(double x)
{
return x*x*x-18;
}
int main()
{
int i;
float a,b;
cout<<"Here is The Equation : \n\n x*x*x-18=0 \n\n";
cout<<"Enter Right Value for A and B : \n";
cin>>a>>b;
if(func(a)<0 && func(b)>0)
{
for(i=1; i<=10; i++)
{
float equation = ((a*a*a)-18);
float differentiate = (3*(a*a));
a-=equation/differentiate;
cout<<"Steps Taken "<<i<<" X="<<a<<endl;
}
}
else
cout<<"You have not Assigned right A and B\n";
return 0;
}
| 859
|
C++
|
.cpp
| 33
| 20.636364
| 100
| 0.577723
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,822
|
False Position.cpp
|
OpenGenus_cosmos/code/numerical_analysis/false_position/src/False Position.cpp
|
#include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation x*x*x-x-1=0 by False Position Method
First we take 2 values from function of the Equation (negative/positive) then place it in a and b;
then we check that if we assigned the right a and b
then we apply False Position Formula
then we iterate this similar way of bisection
*/
double func(double x)
{
return x*x*x-x-1;
}
int main()
{
int n=20,i;
float a,b,x,y;
cout<<"Here is The Equation : \n\n x*x*x-x-1=0 \n\n";
cout<<"Enter Right Value for A and B : \n";
cin>>a>>b;
if (func(a) * func(b) >= 0)
{
cout << "You have not Assigned right A and B\n";
return 0;
}
for(i=1;i<n;i++)
{
x=((a*func(b)-b*func(a))/(func(b)-func(a)));
y=func(x);
if(y==0)cout<<"Steps Taken "<<i<<" X="<<x<<"\n";
else if(y>0)
{
a=a;
b=x;
cout<<"Steps Taken "<<i<<" X="<<x<<"\n";
}
else
{
a=x;
b=b;
cout<<"Steps Taken "<<i<<" X="<<x<<"\n";
}
}
return 0;
}
| 1,155
|
C++
|
.cpp
| 45
| 19.4
| 102
| 0.512217
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,823
|
integral_rectangle.cpp
|
OpenGenus_cosmos/code/numerical_analysis/integral/src/integral_rectangle.cpp
|
#include <iostream>
#include <functional>
//Part of Cosmos by OpenGenus Foundation
double integralRectangle(double a, double b, double step, std::function<double(double)> f)
{
double fragment, res;
fragment = (b - a) / step;
res = step * (f(a) + f(b)) / 6.0;
for (int i = 1; i <= fragment; ++i)
res = res + 4.0 / 6.0 * step * f(a + step * (i - 0.5));
for (int i = 1; i <= fragment - 1; ++i)
res = res + 2.0 / 6.0 * step * f(a + step * i);
return res;
}
int main()
{
double a, b, step, res;
std::cout << "Enter interval: " << std::endl;
std::cout << "a: " << std::endl;
std::cin >> a;
std::cout << "b: " << std::endl;
std::cin >> b;
std::cout << "Enter integration step: " << std::endl;
std::cin >> step;
res = integralRectangle(a, b, step, [](double x) -> double
{
return x;
});
std::cout << "Result: " << res << std::endl;
return 0;
}
| 939
|
C++
|
.cpp
| 31
| 25.967742
| 90
| 0.533702
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,824
|
integral_trapezoid.cpp
|
OpenGenus_cosmos/code/numerical_analysis/integral/src/integral_trapezoid.cpp
|
#include <iostream>
#include <functional>
//Part of Cosmos by OpenGenus Foundation
double integralTrapezoid(double a, double b, double step, std::function<double(double)> f)
{
double fragment, res;
fragment = (b - a) / step;
res = step * (f(a) + f(b)) / 2.0;
for (int i = 1; i <= fragment - 1; ++i)
res = res + step * f(a + step * i);
return res;
}
int main()
{
double a, b, step, res;
std::cout << "Enter interval: " << std::endl;
std::cout << "a: " << std::endl;
std::cin >> a;
std::cout << "b: " << std::endl;
std::cin >> b;
std::cout << "Enter integration step: " << std::endl;
std::cin >> step;
res = integralTrapezoid(a, b, step, [](double x) -> double
{
return x;
});
std::cout << "Result: " << res << std::endl;
return 0;
}
| 822
|
C++
|
.cpp
| 29
| 24.241379
| 90
| 0.553729
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,826
|
Bisection Method.cpp
|
OpenGenus_cosmos/code/numerical_analysis/bisection/src/Bisection Method.cpp
|
#include<bits/stdc++.h>
using namespace std;
/*
Program to Find Root of the equation x*x-2*x-2=0 by Bisection Method
First we take 2 values from function of the Equation (negative/positive) then place it in a and b;
then we check that if we assigned the right a and b
then we apply Bisection Method Formula
then we iterate it N'th Time
*/
double func(double x)
{
return x*x-2*x-2;
}
int main()
{
int n=20,i;
float a,b,x,y;
cout<<"Here is The Equation : \n\n x*x-2*x-2=0 \n\n";
cout<<"Enter Right Value for A and B : \n";
cin>>a>>b;
if(func(a)<0 && func(b)>0)
{
for(i=1;i<n;i++)
{
x=(a+b)/2;
y=(x*x-2*x-2);
if(y==0)cout<<"Steps Taken "<<i<<" x="<<x<<endl;
else if(y>0)
{
a=a;
b=x;
cout<<"Steps Taken "<<i<<" x="<<x<<endl;
}
else
{
a=x;
b=b;
cout<<"Steps Taken "<<i<<" x="<<x<<endl;
}
}
}
else
{
cout << "You have not Assigned right A and B\n";
}
return 0;
}
| 1,111
|
C++
|
.cpp
| 47
| 17.425532
| 102
| 0.50566
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,827
|
rk4.cpp
|
OpenGenus_cosmos/code/numerical_analysis/runge_kutt/src/rk4.cpp
|
#include <iostream>
#include <vector>
#include <functional>
#include <cmath>
using xy = std::pair<double, double>;
std::vector<xy> rungeKutt(xy startConditions,
double startInterval,
double finishInterval,
double step,
std::function<double(double, double)> f)
{
std::vector<xy> res;
unsigned int numberSteps = std::ceil((finishInterval - startInterval) / step);
double k1, k2, k3, k4;
res.reserve(numberSteps + 1);
res.push_back(startConditions);
for (unsigned int i = 0; i < numberSteps; ++i)
{
k1 = step * f(startConditions.first, startConditions.second);
k2 = step * f(startConditions.first + step / 2.0, startConditions.second + k1 / 2.0);
k3 = step * f(startConditions.first + step / 2.0, startConditions.second + k2 / 2.0);
k4 = step * f(startConditions.first + step, startConditions.second + k3 );
startConditions.second += (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0;
startConditions.first += step;
res.push_back(startConditions);
}
return res;
}
int main()
{
xy startConditions;
double startInterval, finishInterval, step;
std::vector<xy> res;
std::cout << "Enter start condition:" << "\n";
std::cout << "X = " << std::endl;
std::cin >> startConditions.first;
std::cout << "Y = " << std::endl;
std::cin >> startConditions.second;
std::cout << "Enter interval:" << "\n";
std::cout << "Start = " << std::endl;
std::cin >> startInterval;
std::cout << "Finish = " << std::endl;
std::cin >> finishInterval;
std::cout << "Enter step: " << std::endl;
std::cin >> step;
auto func = [](double x, double y) -> double
{
return std::pow(x, 2) * (3 * y + std::exp(std::pow(x, 3)));
};
res = rungeKutt(startConditions, startInterval, finishInterval, step, func);
for (auto it = res.begin(); it != res.end(); ++it)
std::cout << "X = " << it->first << " Y = " << it->second << std::endl;
return 0;
}
| 2,125
|
C++
|
.cpp
| 54
| 32.12963
| 93
| 0.569908
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,829
|
pi_monte_carlo.cpp
|
OpenGenus_cosmos/code/numerical_analysis/monte_carlo/src/pi_monte_carlo.cpp
|
#include <iostream>
#include <random>
//Part of Cosmos by OpenGenus Foundation
double piMonteCarlo(double pointCount)
{
double circlePoints = 0;
double pi, x, y;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis;
for (int i = 0; i < pointCount; ++i)
{
x = dis(gen);
y = dis(gen);
if (x * x + y * y < 1)
circlePoints++;
}
pi = (circlePoints / pointCount) * 4;
return pi;
}
int main()
{
double pointCount, pi;
std::cout << "Enter point count: " << std::endl;
std::cin >> pointCount;
pi = piMonteCarlo(pointCount);
std::cout << "Pi = " << pi << std::endl;
return 0;
}
| 701
|
C++
|
.cpp
| 29
| 19.655172
| 52
| 0.58209
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,830
|
integral_monte_carlo.cpp
|
OpenGenus_cosmos/code/numerical_analysis/monte_carlo/src/integral_monte_carlo.cpp
|
#include <iostream>
#include <functional>
#include <random>
//Part of Cosmos by OpenGenus Foundation
double integralMonteCarlo(double a, double b, double pointCount, std::function<double(double)> f)
{
double res, randX, randY;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis;
for (int i = 0; i < pointCount; ++i)
{
randX = ((b - a) * dis(gen)) + a;
randY += f(randX);
}
res = (b - a) * (randY / pointCount);
return res;
}
int main()
{
double a, b, pointCount, res;
std::cout << "Enter interval: " << std::endl;
std::cout << "a: " << std::endl;
std::cin >> a;
std::cout << "b: " << std::endl;
std::cin >> b;
std::cout << "Enter point count: " << std::endl;
std::cin >> pointCount;
res = integralMonteCarlo(a, b, pointCount, [](double x) -> double
{
return x * x + x;
});
std::cout << "Result: " << res << std::endl;
return 0;
}
| 977
|
C++
|
.cpp
| 35
| 23.657143
| 97
| 0.573404
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,832
|
nfa.cpp
|
OpenGenus_cosmos/code/theory_of_computation/src/nondeterministic_finite_atomaton/nfa.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
int row = 0;
struct node
{
int data;
struct node* next;
char edgetype;
}typedef node;
node* push(node* first , char edgetype , int data)
{
node* new_node = (node*)malloc(sizeof(node));
new_node->edgetype = edgetype;
new_node->data = data;
new_node->next = NULL;
if (first==NULL)
{
first = new_node;
return new_node;
}
first->next = push(first->next,edgetype,data);
return first;
}
int nfa(node** graph, int current, char* input,
int* accept, int start)
{
if (start==(int)strlen(input))
return accept[current];
node* temp = graph[current];
while (temp != NULL)
{
if (input[start]==temp->edgetype)
if (nfa(graph,temp->data,input,accept,start+1==1)) return 1;
temp=temp->next;
}
return 0;
}
void generate(char** arr, int size, char *a)
{
if (size==0)
{
strcpy(arr[row], a);
row++;
return;
}
char b0[20] = {'\0'};
char b1[20] = {'\0'};
b0[0] = '0';
b1[0] = '1';
generate((char**)arr, size-1, strcat(b0,a));
generate((char**)arr, size-1, strcat(b1,a));
return;
}
int main()
{
int n;
int i, j;
scanf("%d", &n);
node* graph[n+1];
for (i=0;i<n+1;i++)
graph[i]=NULL;
int accept[n+1];
for (i=0; i<n; i++)
{
int index,acc,number_nodes;
scanf("%d%d%d",&index,&acc,&number_nodes);
accept[index]=acc;
for (j=0;j<number_nodes;j++)
{
int node_add;
int edge;
scanf("%d%d",&edge,&node_add);
graph[index] = push(graph[index],'0'+edge,node_add);
}
}
int size = 1, count = 0;
if (accept[1]==1)
{
printf("e\n");
count++;
}
while (count < 11)
{
char** arr;
int power = pow(2,size);
arr = (char**)malloc(power*sizeof(char*));
for (i=0;i<power;i++)
arr[i] = (char*)malloc(size*sizeof(char));
char a[20] = {'\0'};
generate((char**)arr,size,a);
for (i=0; i<power; i++)
{
char input[20] = {'\0'};
for (j=0; j<size; j++)
{
char foo[2];
foo[0] = arr[i][size-1-j];
foo[1] = '\0';
strcat(input,foo);
}
int result = nfa(graph,1,input,accept,0);
if (result==1)
{
printf("%s\n",input);
count++;
}
if (count==10)
return 0;
}
size++;
row=0;
}
return 0;
}
| 2,339
|
C++
|
.cpp
| 117
| 16.230769
| 69
| 0.566621
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,833
|
dfa.cpp
|
OpenGenus_cosmos/code/theory_of_computation/src/deterministic_finite_automaton/dfa.cpp
|
#include "dfa.hh"
#include <stdlib.h>
#include <string.h>
using namespace std;
void dfa_makeNextTransition(dfa* dfa, char symbol)
{
int transitionID;
DFAState* pCurrentState = dfa->states[dfa->currentStateID];
for (transitionID = 0; transitionID < pCurrentState->numberOfTransitions; transitionID++)
{
if (pCurrentState->transitions[transitionID].condition(symbol))
{
dfa->currentStateID = pCurrentState->transitions[transitionID].toStateID;
return;
}
}
dfa->currentStateID = pCurrentState->defaultToStateID;
}
void dfa_addState(dfa* pDFA, dfaState* newState)
{
newState->id = pDFA->noOfStates;
pDFA->states[pDFA->noOfStates] = newState;
pDFA->noOfStates++;
}
void dfa_addTransition(DFA* dfa, int fromStateID, int(*condition)(char), int toStateID)
{
DFAState* state = dfa->states[fromStateID];
state->transitions[state->noOfTransitions].condition = condition;
state->transitions[state->noOfTransitions].toStateID = toStateID;
state->noOfTransitions++;
}
dfaState* dfa_createState(bool actionable, std::string actionName)
{
dfaState* newState = (dfaState*)malloc(sizeof(dfaState));
strcpy(newState->actionName, actionName);
newState->defaultToStateID = -1;
newState->actionable = actionable;
newState->id = -1;
newState->noOfTransitions = 0;
return newState;
}
dfa* dfa_createDFA()
{
dfa* dfa = (dfa*)malloc(sizeof(dfa));
dfa->noOfStates = 0;
dfa->startStateID = -1;
dfa->currentStateID = -1;
return dfa;
}
void dfa_reset(dfa* dfa)
{
dfa->currentStateID = dfa->startStateID;
}
| 1,525
|
C++
|
.cpp
| 53
| 26.849057
| 90
| 0.764022
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,834
|
vector-to-map.cpp
|
OpenGenus_cosmos/code/languages/cpp/vector-to-map.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
map<string,int> mp1;
mp1["Shivani"] = 500;
mp1["Kumari"] = 100;
mp1["Hacktoberfest"] = 400;
vector<pair<string,int>> vec1;
for(auto i : mp1) //inserting map values into vector
{
vec1.push_back(make_pair(i.first,i.second));
}
for(auto j : vec1)
cout<<j.first<<" : "<<j.second<<endl;
return 0;
}
| 363
|
C++
|
.cpp
| 16
| 21.1875
| 54
| 0.682216
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,835
|
Largest_element.cpp
|
OpenGenus_cosmos/code/languages/cpp/largest-element-in-an-array/Largest_element.cpp
|
#include <iostream>
using namespace std;
int findlargestelement(int arr[], int n){
int largest = arr[0];
for(int i=0; i<n; i++) {
if(largest<arr[i]) {
largest=arr[i];
}
}
return largest;
}
int main() {
int n;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
cout<<"Enter array elements: ";
for(int i=0; i<n; i++){
cin>>arr[i];
}
int largest = findlargestelement(arr, n);
cout<<"largest Element is: "<<largest;
return 0;
}
| 506
|
C++
|
.cpp
| 24
| 16.833333
| 44
| 0.578616
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,838
|
sorting_vector.cpp
|
OpenGenus_cosmos/code/languages/cpp/sort_vector/sorting_vector.cpp
|
//sorting using vectors
#include<bits/stdc++.h>
using namespace std;
int main;
{
vector<int> v;
cout<<"size of array"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
v.push_back(i);
}
for(int i=0;i<n;i++)
{
cout<<v[i]<<" ";
}
sort(v.begin(),vec.end());
for(int x:v)
{
cout<<x<<" ";
}
return 0;
}
| 326
|
C++
|
.cpp
| 23
| 11.434783
| 30
| 0.547855
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,839
|
multimap.cpp
|
OpenGenus_cosmos/code/languages/cpp/initializing_multimap/multimap.cpp
|
#include<iostream>
#include<cstdlib>
#include<map>
using namespace std;
int main()
{
//common way to initialize a multimap
std::multimap<char, int> m; //empty multimap container
m.insert({'a',1}); //inserting (a,1)
m.insert({'a',1}); //inserting (a,1)
m.insert({'b',2}); //inserting (b,2)
m.insert({'c',3}); //inserting (c,3)
m.insert({'a',2}); //inserting (a,2)
m.insert({'d',4}); //inserting (d,4)
//Method 1
std::multimap<char, int> m; //empty multimap container
m.insert(make_pair('a',1)); //inserting (a,1)
m.insert(make_pair('a',1)); //inserting (a,1)
m.insert(make_pair('b',2)); //inserting (b,2)
m.insert(make_pair('c',3)); //inserting (c,3)
m.insert(make_pair('a',2)); //inserting (a,2)
m.insert(make_pair('d',4)); //inserting (d,4)
//Method 2
pair<char, int> x;
std::multimap<char, int> m; //empty multimap container
x.first='a';x.second=1;
m.insert(x); //inserting (a,1)
x.first='a';x.second=1;
m.insert(x); //inserting (a,1)
x.first='b';x.second=2;
m.insert(x); //inserting (b,2)
x.first='c';x.second=3;
m.insert(x); //inserting (c,3)
x.first='a';x.second=2;
m.insert(x); //inserting (a,2)
x.first='d';x.second=4;
m.insert(x); //inserting (d,4)
//Method 3
std::multimap<char, int> m; //empty multimap container
m.insert(pair<char, int>('a',1)); //inserting (a,1)
m.insert(pair<char, int>('a',1)); //inserting (a,1)
m.insert(pair<char, int>('b',2)); //inserting (b,2)
m.insert(pair<char, int>('c',3)); //inserting (c,3)
m.insert(pair<char, int>('a',2)); //inserting (a,2)
m.insert(pair<char, int>('d',4)); //inserting (d,4)
//Method 4
std::multimap<char, int> m={
{'a',1}, {'a',1}, {'b',2}, {'c',3}, {'a',2}, {'d',4}
};
//Method 5
std::multimap<char, int> n(m.begin(),m.end());
//Method 6
std::multimap<char, int> n(m);
//Method 7
std::multimap<char, int> mp;
mp.emplace_hint(mp.begin(), 'a', 1);
mp.emplace_hint(mp.begin(), 'a', 1);
mp.emplace_hint(mp.begin(), 'b', 2);
mp.emplace_hint(mp.begin(), 'c', 3);
mp.emplace_hint(mp.begin(), 'a', 2);
mp.emplace_hint(mp.begin(), 'd', 4);
//Printing contents of the multimap :
//Method 1
for(auto& el : mp)
cout<<el.first<<" "<<el.second<<endl;
//Method 2
multimap<char, int>::iterator it;
for(it=m.begin();it!=m.end();it++)
cout<<it->first<<" "<<it->second<<"\n";
//Method 3
for(pair<char, int> elem: m)
cout<<elem.first<<" "<<elem.second<<endl;
return 0;
}
| 2,711
|
C++
|
.cpp
| 74
| 31.472973
| 60
| 0.546045
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,841
|
begin_and_end.cpp
|
OpenGenus_cosmos/code/languages/cpp/begin_and_end/begin_and_end.cpp
|
// Implementation of begin() function
#include <array>
#include <iostream>
using namespace std;
int main()
{
// declaration of array container
array<int, 5> myarray{ 1, 2, 3, 4, 5 };
// using begin() to print array
for (auto it = myarray.begin(); it! =myarray. end(); ++it)
cout << ' ' << *it;
return 0;
}
// Implementation of end() function
#include <array>
#include <iostream>
using namespace std;
int main()
{
// declaration of array container
array<int, 5> myarray{ 10, 20, 30, 40, 50 };
// using end() to print array
for (auto it = myarray.begin();
it != myarray.end(); ++it)
cout << ' ' << *it;
return 0;
}
| 661
|
C++
|
.cpp
| 27
| 21.703704
| 60
| 0.632166
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,844
|
Linear Search In A LinkedList With Duplicates.cpp
|
OpenGenus_cosmos/code/languages/cpp/linear_search/Linear Search In A LinkedList With Duplicates.cpp
|
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *nptr; // next pointer
};
struct node *hptr = NULL; // head pointer
void insert(int pos, int x)
{
struct node *temp = new node;
if (temp == NULL)
cout<<"Insertion not possible\n";
temp->data = x; // storing the value in data field
if (pos == 1)
{
temp->nptr = hptr;
hptr = temp;
}
else
{
int i = 1;
struct node *thptr = hptr; // temporary pointer
while (i < pos - 1)
{
thptr = thptr->nptr; // traversing to the position of insertion
i++;
}
temp->nptr = thptr->nptr;
thptr->nptr = temp;
}
}
void print()
{
struct node *temp = hptr;
cout<<"Linked List contains : \n";
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->nptr;
}
}
int ind;
int *linearSearch(int key, int result[])
{
struct node *temp = hptr;
int i = 1;
ind = 0;
while (temp != NULL)
{
if (temp->data == key)
{
result[ind++] = i;
}
else
{
result[ind] = -1;
ind++;
}
i++;
temp = temp->nptr;
}
return result;
}
int main()
{
int result[10];
insert(1, 11);
insert(2, 6);
insert(3, 12);
insert(4, 14);
insert(5, 6);
insert(6, 10);
insert(7, 6);
print();
printf("\nPosition(s) of the key is : ");
linearSearch(6, result);
for (int i = 0; i < ind; i++)
{
if (result[i] != -1)
cout<<result[i]<<" ";
}
return 0;
}
| 1,658
|
C++
|
.cpp
| 84
| 14.011905
| 75
| 0.493308
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,845
|
Linear Search In Duplicate Array.cpp
|
OpenGenus_cosmos/code/languages/cpp/linear_search/Linear Search In Duplicate Array.cpp
|
// C++ code to linearly search x in arr[].
//If x is present then return its location, otherwise return -1
#include <iostream>
using namespace std;
int *linearSearch(int arr[], int result[], int N, int x)
{
int pos = -1, ind = 0;
for (int i = 0; i <N; ++i)
{
if (arr[i] == x)
{
result[ind++] = i+1; // store the index of key, if found
}
else
result[ind++] = -1; // store -1 if key not found
}
return result;
}
// Driver's code
int main(void)
{
int arr[] = {2, 3, 4, 10, 40, 3, 10, 2, 10 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
int result[N];
linearSearch(arr, result, N, x);
int size = sizeof(result) / sizeof(result[0]);
cout<<"Key found at position(s) : \n";
for (int i = 0; i < size; i++)
{
if (result[i] != -1)
cout<<result[i]<<" ";
}
return 0;
}
| 910
|
C++
|
.cpp
| 35
| 20.828571
| 68
| 0.525892
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,848
|
free_vs_delete.cpp
|
OpenGenus_cosmos/code/languages/cpp/delete_vs_free/free_vs_delete.cpp
|
//Example of free() function using malloc and realloc:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
char *ptr;
ptr = (char*) malloc(10*sizeof(char)); //Allocating memory to thr character pointer
strcpy(ptr,"Hello C++");
cout << "Before reallocating: " << ptr << endl;
ptr = (char*) realloc(ptr,20); //Reallocating memory
strcpy(ptr,"Hello, Welcome to C++");
cout << "After reallocating: " <<ptr << endl;
free(ptr); //Freeing the character pointer
cout << endl << "Garbage Value: " << ptr;
return 0;
}
// Example of deleting a single object:
#include<iostream>
using namespace std;
int main()
{
int *d = new int(10); //Integer object created
cout<< "The value at the address pointed by the pointer variable : " << *d << "\n";
cout<< "The memory address allocated to the pointer variable : " << d << "\n";
delete d; //Single integer object deleted
cout<< "The value at the address pointed by pointer variable : " << *d << "\n";
cout<< "The memory address allocated to the pointer variable : " << d;
}
//Example of deleting multiple objects:
#include<iostream>
using namespace std;
int main()
{
int *d = new int[100]; //creation of multiple objects
delete [] d; //deletion of multiple objects
}
| 1,450
|
C++
|
.cpp
| 38
| 36.105263
| 96
| 0.612347
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,850
|
int8_t_test.cpp
|
OpenGenus_cosmos/code/languages/cpp/uint8_t/int8_t_test.cpp
|
#include <iostream>
int main() {
uint8_t number = 4;
std::cout << "Number=" << +number << std::endl;
return 0;
}
| 119
|
C++
|
.cpp
| 6
| 17.833333
| 49
| 0.60177
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,851
|
double_to_str.cpp
|
OpenGenus_cosmos/code/languages/cpp/double_to_string/double_to_str.cpp
|
//double to String using C++’s std::to_string:
#include <iostream>
#include <string>
#include <sstream> //to use ostringstream
#include <cstring> //to use sprintf
#include <boost/lexical_cast.hpp> //to use boost's lexical cast
using namespace std;
int main()
{
double d1 = 23.43;
double d2 = 1e-9;
double d3 = 1e40;
double d4 = 1e-40;
double d5 = 123456789;
string d_str1 = to_string(d1);
string d_str2 = to_string(d2);
string d_str3 = to_string(d3);
string d_str4 = to_string(d4);
string d_str5 = to_string(d5);
cout << "Number: " << d1 << '\n'
<< "to_string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to_string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to_string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to_string: " << d_str4 << "\n\n"
<< "Number: " << d5 << '\n'
<< "to_string: " << d_str5 << '\n';
//double to String using ostringstream
ostringstream ss1,ss2,ss3,ss4;
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
ss1<<d1;
ss2<<d2;
ss3<<d3;
ss4<<d4;
string d_str1 = ss1.str();
string d_str2 = ss2.str();
string d_str3 = ss3.str();
string d_str4 = ss4.str();
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n";
//Code to convert double to string with osstringstream to get the output as fixed-point notation inplace of scientific notation.
ostringstream ss1,ss2,ss3,ss4;
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
ss1<<fixed<<d1;
ss2<<fixed<<d2;
ss3<<fixed<<d3;
ss4<<fixed<<d4;
string d_str1 = ss1.str();
string d_str2 = ss2.str();
string d_str3 = ss3.str();
string d_str4 = ss4.str();
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n";
//double to string with custom precision by setting the precision in stringstream as below
ostringstream ss1,ss2,ss3,ss4;
ss1.precision(2);
ss2.precision(2);
ss3.precision(2);
ss4.precision(2);
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
ss1<<fixed<<d1;
ss2<<fixed<<d2;
ss3<<fixed<<d3;
ss4<<fixed<<d4;
string d_str1 = ss1.str();
string d_str2 = ss2.str();
string d_str3 = ss3.str();
string d_str4 = ss4.str();
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n";
//double to String/character array using sprintf
double d1 = 23.43;
double d2 = 6789898989.339994;
double d3 = 1e40;
double d4 = 1e-40;
char s[200];
sprintf(s," 23.43 converts to %.2f \n 6789898989.339994 converts to %.3f \n 1e40 converts to %.4f \n 1e-40 converts to %.5f",d1,d2,d3,d4);
cout<<s<<"\nsize of the above string is:"<<strlen(s);
//double to String using boost’s lexical_cast
double d1 = 23.43;
double d2 = 1e-9;
double d3 = 1e40;
double d4 = 1e-40;
double d5 = 123456789;
string d_str1 = boost::lexical_cast<string>(d1);
string d_str2 = boost::lexical_cast<string>(d2);
string d_str3 = boost::lexical_cast<string>(d3);
string d_str4 = boost::lexical_cast<string>(d4);
string d_str5 = boost::lexical_cast<string>(d5);
cout << "Number: " << d1 << '\n'
<< "to string: " << d_str1 << "\n\n"
<< "Number: " << d2 << '\n'
<< "to string: " << d_str2 << "\n\n"
<< "Number: " << d3 << '\n'
<< "to string: " << d_str3 << "\n\n"
<< "Number: " << d4 << '\n'
<< "to string: " << d_str4 << "\n\n"
<< "Number: " << d5 << '\n'
<< "to string: " << d_str5 << '\n';
return 0;
}
| 4,389
|
C++
|
.cpp
| 130
| 28.938462
| 142
| 0.530675
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,852
|
continue.cpp
|
OpenGenus_cosmos/code/languages/cpp/loop/continue.cpp
|
#include <iostream>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==5)
{
/* The continue statement is encountered when
* the value of j is equal to 5.
*/
continue;
}
/* This print statement would not execute for the
* loop iteration where j ==5 because in that case
* this statement would be skipped.
*/
std::cout << j;
}
return 0;
}
/*
0 1 2 3 4 6 7 8
*/
| 428
|
C++
|
.cpp
| 23
| 14.478261
| 56
| 0.568238
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,853
|
life.cpp
|
OpenGenus_cosmos/code/cellular_automaton/src/conways_game_of_life/life.cpp
|
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Defines the world size parameters
const int SIZE_X = 50;
const int SIZE_Y = 160;
// Number of random cells are filled
const int number = SIZE_X * SIZE_Y / 8;
void loadConfig(char world[][SIZE_Y]);
// Initializes world and loads up several default values
void generation(char world[][SIZE_Y], int& gen);
// Takes the world array and decides whether cells live, die, or multiply.
void copyGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y]);
// Copies the current generation from world to worldCopy.
void updateGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y]);
// Updates the current generation in worldCopy to world.
void display(const char world[][SIZE_Y], ofstream& fout, const int gen);
// Outputs the world as text.
// Records each successive world generation in a text file.
int getNeighbors(const char world[][SIZE_Y], int posX, int posY);
// Retrieves the amount of neighbors a cell has
int main()
{
int gen(0);
char world[SIZE_X][SIZE_Y];
ofstream fout;
fout.open("life.txt");
if (fout.fail())
{
cout << "Opening file for output failed!\n";
exit(1);
}
loadConfig(world);
display(world, fout, gen);
char c;
cout << "\nPress return to create a new generation and press x to exit!\n";
cin.get(c);
while (c == '\n') {
generation(world, gen);
display(world, fout, gen);
cout << "\nPress return to create a new generation and press x to exit!\n";
cin.get(c);
}
return 0;
}
void loadConfig(char world[][SIZE_Y])
{
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
world[i][j] = '-';
srand(time(NULL));
for (int i = 0; i < number; i++)
{
int randX = rand() % SIZE_X;
int randY = rand() % SIZE_Y;
world[randX][randY] = '*';
}
}
int getNeighbors(const char world[][SIZE_Y], int posX, int posY)
{
int neighbors(0);
int row = posX - 1, column = posY - 1;
// Top-left
if (column >= 0 && row >= 0)
if (world[row][column] == '*')
neighbors++;
// Top-middle
column++;
if (row >= 0)
if (world[row][column] == '*')
neighbors++;
// Top-right
column++;
if (column < SIZE_Y && row >= 0)
if (world[row][column] == '*')
neighbors++;
row = posX, column = posY; // Reset
// Left
column--;
if (column >= 0)
if (world[row][column] == '*')
neighbors++;
// Right
column = posY + 1;
if (column < SIZE_Y)
if (world[row][column] == '*')
neighbors++;
row = posX + 1, column = posY - 1; // Reset
// Bottom-left
if (row < SIZE_X && column >= 0)
if (world[row][column] == '*')
neighbors++;
column++;
if (row < SIZE_X)
if (world[row][column] == '*')
neighbors++;
column++;
if (row < SIZE_X && column < SIZE_Y)
if (world[row][column] == '*')
neighbors++;
return neighbors;
}
void generation(char world[][SIZE_Y], int& gen)
{
char worldCopy[SIZE_X][SIZE_Y];
copyGeneration(world, worldCopy);
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
{
int neighbors = getNeighbors(world, i, j);
if (neighbors <= 1 || neighbors > 3)
worldCopy[i][j] = '-';
else if (neighbors == 3 && worldCopy[i][j] == '-')
worldCopy[i][j] = '*';
}
updateGeneration(world, worldCopy);
gen++;
}
void copyGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y])
{
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
worldCopy[i][j] = world[i][j];
}
void updateGeneration(char world[][SIZE_Y], char worldCopy[][SIZE_Y])
{
for (int i = 0; i < SIZE_X; i++)
for (int j = 0; j < SIZE_Y; j++)
world[i][j] = worldCopy[i][j];
}
void display(const char world[][SIZE_Y], ofstream& fout, const int gen)
{
cout << "Generation " << gen << endl;
fout << 'G' << ' ' << gen << '\n';
for (int i = 0; i < SIZE_X; i++)
{
for (int j = 0; j < SIZE_Y; j++)
{
char cell = world[i][j];
cout << cell;
fout << cell;
}
cout << endl;
fout << '\n';
}
cout << endl;
fout << '\n';
}
| 4,512
|
C++
|
.cpp
| 150
| 24.26
| 83
| 0.549712
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
9,854
|
genetic.cpp
|
OpenGenus_cosmos/code/cellular_automaton/src/genetic_algorithm/genetic.cpp
|
/**
* Root finding using genetic algorithm (Uses C++11).
* Reference: https://arxiv.org/abs/1703.03864
*/
#include <algorithm>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>
struct StopCondition
{
StopCondition(double tol, long iter)
: tolerance(tol)
, iterations(iter)
{
}
double tolerance;
long iterations;
};
struct GAConfig
{
GAConfig(double learning_rate, double variance, long generation_size)
: lr(learning_rate)
, var(variance)
, size(generation_size)
{
factor = lr / (var * size);
}
double lr;
double var;
long size;
double factor;
};
template <typename UnaryFunc>
double solve(UnaryFunc f, double initial, GAConfig conf, StopCondition cond)
{
std::default_random_engine gen;
std::normal_distribution<double> normal(0, 1);
std::vector<double> noise(conf.size);
std::vector<double> generation(conf.size);
std::vector<double> fitness(conf.size);
double x = initial, error = 0;
long iter = 0;
do {
double delta = 0;
for (int i = 0; i < conf.size; ++i)
{
noise[i] = normal(gen);
generation[i] = x + conf.var * noise[i];
fitness[i] = exp(-abs(f(generation[i])));
delta += fitness[i] * noise[i];
}
x = x + conf.factor * delta;
error = std::abs(f(x));
std::cout << iter + 1 << "\tx = " << x << "\t error = " << error
<< std::endl;
} while ((error > cond.tolerance) && (++iter < cond.iterations));
return x;
}
int main()
{
auto f = [](double x)
{
return (x - 1.0) * (x - 2.0);
};
auto config = GAConfig{ 0.2, 0.1, 10 };
auto stop_condition = StopCondition{ 1e-3, 10000 };
double solution = solve(f, 0.0, config, stop_condition);
std::cout << solution << std::endl;
}
| 1,929
|
C++
|
.cpp
| 70
| 21.771429
| 76
| 0.576299
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,855
|
langtons_ant.cpp
|
OpenGenus_cosmos/code/cellular_automaton/src/langtons_ant/langtons_ant.cpp
|
#include <iostream>
#include <vector>
#include <array>
using std::cout;
using std::cin;
using std::vector;
using std::array;
class Direction
{
public:
int x;
int y;
const static Direction north;
const static Direction east;
const static Direction south;
const static Direction west;
const static array<Direction, 4> directions;
private:
int i;
private:
Direction(int x_, int y_, int i_)
{
x = x_;
y = y_;
i = i_;
};
public:
Direction() : Direction(north)
{
};
Direction right() const
{
return directions.at((this->i + 1) % 4);
}
Direction left() const
{
return directions.at((this->i + 3) % 4);
}
};
const Direction Direction::north{0, 1, 0};
const Direction Direction::east{1, 0, 1};
const Direction Direction::south{0, -1, 2};
const Direction Direction::west{-1, 0, 3};
const array<Direction, 4> Direction::directions({
north, east, south, west,
});
class LangtonAnt
{
private:
vector<vector<unsigned char>> board;
int ant_x;
int ant_y;
int width;
int height;
Direction direction;
public:
LangtonAnt(int width_, int height_)
{
board.assign(width_, vector<unsigned char>(height_, 0));
width = width_;
height = height_;
ant_x = width / 2;
ant_y = height / 2;
}
void show()
{
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
cout << (board[j][i] ? '#' : ' ');
cout << '\n';
}
}
void step()
{
if (board[ant_x][ant_y])
{
board[ant_x][ant_y] = 0;
direction = direction.left();
}
else
{
board[ant_x][ant_y] = 1;
direction = direction.right();
}
ant_x = (ant_x + direction.x + width) % width;
ant_y = (ant_y + direction.y + height) % height;
}
};
int main()
{
const int width = 100;
const int height = 50;
const int max_step = 10000;
LangtonAnt langtonAnt(width, height);
for (int step = 0; step <= max_step; ++step)
{
cout << "Step " << step << '\n';
langtonAnt.show();
cin.get();
langtonAnt.step();
}
}
| 2,293
|
C++
|
.cpp
| 103
| 16.640777
| 64
| 0.545078
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,857
|
baconian_test.cpp
|
OpenGenus_cosmos/code/cryptography/test/baconian_cipher/baconian_test.cpp
|
#include <assert.h>
#include <iostream>
#include "./../../src/baconian_cipher/baconian.cpp"
// Part of Cosmos by OpenGenus Foundation
int main()
{
std::string baconianString = "AABBBAABAAABABBABABBABBBA BABBAABBBABAAABABABBAAABB";
std::string englishString = "HELLO WORLD";
std::map<char, std::string> generatedCipher = createBaconianMap();
assert(encrypt(generatedCipher, englishString) == baconianString);
assert(decrypt(generatedCipher, baconianString) == englishString);
std::cout << "Testing Complete\n";
}
| 537
|
C++
|
.cpp
| 13
| 38.384615
| 87
| 0.751434
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,864
|
aes_128.cpp
|
OpenGenus_cosmos/code/cryptography/src/aes_128/aes_128.cpp
|
/*
* National University from Colombia
* Author:Andres Vargas, Jaime
* Gitub: https://github.com/jaavargasar
* webpage: https://jaavargasar.github.io/
* Language: C++
*
* Description: Given an array 1 ( outpu1 ), an array2 (output2) and a key
* we gotta decipher the messege and read what the messege is as a plane text.
* we're gonna do this with the Algorithm AES 128
*
* original plane text:Paranoia is our profession
*/
#include <iostream>
using namespace std;
//S-box
const unsigned char sbox[256] =
{0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16};
//Inverted S-box
const unsigned char isbox[256] =
{0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d};
//E Table
const unsigned char etable[256] =
{0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF, 0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35,
0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4, 0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA,
0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26, 0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31,
0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC, 0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD,
0x4C, 0xD4, 0x67, 0xA9, 0xE0, 0x3B, 0x4D, 0xD7, 0x62, 0xA6, 0xF1, 0x08, 0x18, 0x28, 0x78, 0x88,
0x83, 0x9E, 0xB9, 0xD0, 0x6B, 0xBD, 0xDC, 0x7F, 0x81, 0x98, 0xB3, 0xCE, 0x49, 0xDB, 0x76, 0x9A,
0xB5, 0xC4, 0x57, 0xF9, 0x10, 0x30, 0x50, 0xF0, 0x0B, 0x1D, 0x27, 0x69, 0xBB, 0xD6, 0x61, 0xA3,
0xFE, 0x19, 0x2B, 0x7D, 0x87, 0x92, 0xAD, 0xEC, 0x2F, 0x71, 0x93, 0xAE, 0xE9, 0x20, 0x60, 0xA0,
0xFB, 0x16, 0x3A, 0x4E, 0xD2, 0x6D, 0xB7, 0xC2, 0x5D, 0xE7, 0x32, 0x56, 0xFA, 0x15, 0x3F, 0x41,
0xC3, 0x5E, 0xE2, 0x3D, 0x47, 0xC9, 0x40, 0xC0, 0x5B, 0xED, 0x2C, 0x74, 0x9C, 0xBF, 0xDA, 0x75,
0x9F, 0xBA, 0xD5, 0x64, 0xAC, 0xEF, 0x2A, 0x7E, 0x82, 0x9D, 0xBC, 0xDF, 0x7A, 0x8E, 0x89, 0x80,
0x9B, 0xB6, 0xC1, 0x58, 0xE8, 0x23, 0x65, 0xAF, 0xEA, 0x25, 0x6F, 0xB1, 0xC8, 0x43, 0xC5, 0x54,
0xFC, 0x1F, 0x21, 0x63, 0xA5, 0xF4, 0x07, 0x09, 0x1B, 0x2D, 0x77, 0x99, 0xB0, 0xCB, 0x46, 0xCA,
0x45, 0xCF, 0x4A, 0xDE, 0x79, 0x8B, 0x86, 0x91, 0xA8, 0xE3, 0x3E, 0x42, 0xC6, 0x51, 0xF3, 0x0E,
0x12, 0x36, 0x5A, 0xEE, 0x29, 0x7B, 0x8D, 0x8C, 0x8F, 0x8A, 0x85, 0x94, 0xA7, 0xF2, 0x0D, 0x17,
0x39, 0x4B, 0xDD, 0x7C, 0x84, 0x97, 0xA2, 0xFD, 0x1C, 0x24, 0x6C, 0xB4, 0xC7, 0x52, 0xF6, 0x01};
//L ,Table
const unsigned char ltable[256] =
{0x00, 0x00, 0x19, 0x01, 0x32, 0x02, 0x1A, 0xC6, 0x4B, 0xC7, 0x1B, 0x68, 0x33, 0xEE, 0xDF, 0x03,
0x64, 0x04, 0xE0, 0x0E, 0x34, 0x8D, 0x81, 0xEF, 0x4C, 0x71, 0x08, 0xC8, 0xF8, 0x69, 0x1C, 0xC1,
0x7D, 0xC2, 0x1D, 0xB5, 0xF9, 0xB9, 0x27, 0x6A, 0x4D, 0xE4, 0xA6, 0x72, 0x9A, 0xC9, 0x09, 0x78,
0x65, 0x2F, 0x8A, 0x05, 0x21, 0x0F, 0xE1, 0x24, 0x12, 0xF0, 0x82, 0x45, 0x35, 0x93, 0xDA, 0x8E,
0x96, 0x8F, 0xDB, 0xBD, 0x36, 0xD0, 0xCE, 0x94, 0x13, 0x5C, 0xD2, 0xF1, 0x40, 0x46, 0x83, 0x38,
0x66, 0xDD, 0xFD, 0x30, 0xBF, 0x06, 0x8B, 0x62, 0xB3, 0x25, 0xE2, 0x98, 0x22, 0x88, 0x91, 0x10,
0x7E, 0x6E, 0x48, 0xC3, 0xA3, 0xB6, 0x1E, 0x42, 0x3A, 0x6B, 0x28, 0x54, 0xFA, 0x85, 0x3D, 0xBA,
0x2B, 0x79, 0x0A, 0x15, 0x9B, 0x9F, 0x5E, 0xCA, 0x4E, 0xD4, 0xAC, 0xE5, 0xF3, 0x73, 0xA7, 0x57,
0xAF, 0x58, 0xA8, 0x50, 0xF4, 0xEA, 0xD6, 0x74, 0x4F, 0xAE, 0xE9, 0xD5, 0xE7, 0xE6, 0xAD, 0xE8,
0x2C, 0xD7, 0x75, 0x7A, 0xEB, 0x16, 0x0B, 0xF5, 0x59, 0xCB, 0x5F, 0xB0, 0x9C, 0xA9, 0x51, 0xA0,
0x7F, 0x0C, 0xF6, 0x6F, 0x17, 0xC4, 0x49, 0xEC, 0xD8, 0x43, 0x1F, 0x2D, 0xA4, 0x76, 0x7B, 0xB7,
0xCC, 0xBB, 0x3E, 0x5A, 0xFB, 0x60, 0xB1, 0x86, 0x3B, 0x52, 0xA1, 0x6C, 0xAA, 0x55, 0x29, 0x9D,
0x97, 0xB2, 0x87, 0x90, 0x61, 0xBE, 0xDC, 0xFC, 0xBC, 0x95, 0xCF, 0xCD, 0x37, 0x3F, 0x5B, 0xD1,
0x53, 0x39, 0x84, 0x3C, 0x41, 0xA2, 0x6D, 0x47, 0x14, 0x2A, 0x9E, 0x5D, 0x56, 0xF2, 0xD3, 0xAB,
0x44, 0x11, 0x92, 0xD9, 0x23, 0x20, 0x2E, 0x89, 0xB4, 0x7C, 0xB8, 0x26, 0x77, 0x99, 0xE3, 0xA5,
0x67, 0x4A, 0xED, 0xDE, 0xC5, 0x31, 0xFE, 0x18, 0x0D, 0x63, 0x8C, 0x80, 0xC0, 0xF7, 0x70, 0x07};
const unsigned char Rcon[11] = {
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};
const unsigned char invMix[4][4] =
{ {0x0e, 0x0b, 0x0d, 0x09},
{0x09, 0x0e, 0x0b, 0x0d},
{0x0d, 0x09, 0x0e, 0x0b},
{0x0b, 0x0d, 0x09, 0x0e} };
unsigned char ini_keys[4][4] =
{ {0x2b, 0x28, 0xab, 0x09},
{0x7e, 0xae, 0xf7, 0xcf},
{0x15, 0xd2, 0x15, 0x4f},
{0x16, 0xa6, 0x88, 0x3c} };
unsigned char output1[4][4] =
{ {0x11, 0xe1, 0xa4, 0x50},
{0x04, 0x63, 0x26, 0x4b},
{0x14, 0x67, 0x92, 0x7d},
{0xd9, 0xce, 0x82, 0xae} };
unsigned char output2[4][4] =
{ {0xb2, 0x51, 0x2b, 0x48},
{0x7e, 0x0c, 0x11, 0xc1},
{0x32, 0x0f, 0xee, 0x38},
{0xee, 0x1a, 0x9d, 0x06} };
unsigned char keys[44][4];
// ----------------------------------- KEYS --------------------------------(begin)
//inicialize the key arrays
void init()
{
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
keys[i][j] = ini_keys[i][j];
}
//rotate the keys through the left
void shitrow(int pos )
{
int aux = pos + 4;
for (int i = aux; i < aux + 3; i++)
keys[i][3] = keys[++pos][3];
keys[aux + 3][3] = keys[pos - 3][3];
}
//do the subword
void subword(const int& pos)
{
int aux = pos + 4;
for (int i = aux; i < aux + 4; i++)
keys[i][3] = sbox[ keys[i][3] ];
}
//do the rcon step
void rcon(const int& pos, const int& index )
{
int aux = pos + 4;
keys[aux][3] ^= Rcon[ index];
}
//create a new round key
void newKey(int pos)
{
int org = pos;
int aux = pos + 4, ini = 3;
for (int k = 0; k < 4; k++)
{
ini = (ini + 1) % 4;
pos = org;
for (int i = aux; i < aux + 4; i++)
keys[i][ini] = ( keys[pos++][ini] ^ keys[i][ (ini + 4 - 1) % 4 ] );
}
}
//find all the posible keys
void expandkeys()
{
int cnt = 1;
for (int i = 0; i < 44; i = i + 4)
{
shitrow(i);
subword(i);
rcon(i, cnt++);
newKey(i);
}
}
void findAllKeys()
{
//we gotta find first all the keys
init();
expandkeys();
}
// ----------------------------------- KEYS --------------------------------(end)
//---------------------------------Decrypt--------------------------------(begin)
//do the add round key
void addRoundKey(int pos)
{
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
output1[i][j] ^= ( keys[pos + i][j] );
output2[i][j] ^= ( keys[pos + i][j] );
}
}
//roate the state through the right by rows
void shifrigth( )
{
for (int i = 1; i <= 2; i++)
for (int j = 3; j >= i; j--)
{
swap( output1[i][j], output1[i][j - i] );
swap( output2[i][j], output2[i][j - i] );
}
for (int j = 0; j < 3; j++)
{
swap(output1[3][j], output1[3][j + 1] );
swap(output2[3][j], output2[3][j + 1] );
}
}
// do the inverse of the subword
void invsubWord( )
{
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
output1[i][j] = isbox[ output1[i][j] ];
output2[i][j] = isbox[ output2[i][j] ];
}
}
//do galois field
unsigned char gaz(unsigned char a, unsigned char b)
{
return etable [ (ltable[a] + ltable[b]) % 0xFF ];
}
//do mix colums step
void mixColums()
{
unsigned char aux[4][4];
unsigned char aux2[4][4];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
aux[j][i] = gaz( output1[0][i], invMix[j][0]) ^ gaz( output1[1][i], invMix[j][1]) ^ gaz(
output1[2][i], invMix[j][2]) ^ gaz( output1[3][i], invMix[j][3]);
aux2[j][i] =
gaz( output2[0][i],
invMix[j][0]) ^
gaz( output2[1][i],
invMix[j][1]) ^
gaz( output2[2][i], invMix[j][2]) ^ gaz( output2[3][i], invMix[j][3]);
}
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
output1[i][j] = aux[i][j];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
output2[i][j] = aux2[i][j];
}
//print the state in hexadecimal
void print()
{
for (int i = 0; i < 4; i++)
{
cout << endl;
for (int j = 0; j < 4; j++)
cout << hex << output1[i][j] << " ";
//cout<<hex<<output2[i][j]<<" ";
}
cout << endl;
}
//Decipher Algorithm
void decrypt( )
{
addRoundKey(40);
shifrigth();
invsubWord();
addRoundKey(36);
for (int i = 32; i >= 0; i = i - 4)
{
mixColums();
shifrigth();
invsubWord();
addRoundKey(i);
}
}
//---------------------------------Decrypt--------------------------------(end)
//main
int main()
{
findAllKeys(); //given a initial key
decrypt(); //AES 128
//print the plan text of the output1
for (int i = 0; i < 4; i++)
{
cout << endl;
for (int j = 0; j < 4; j++)
cout << output1[j][i] << " ";
}
cout << endl;
//print plan text of output2
for (int i = 0; i < 4; i++)
{
cout << endl;
for (int j = 0; j < 4; j++)
cout << output2[j][i] << " ";
}
return 0;
}
| 12,097
|
C++
|
.cpp
| 286
| 37.979021
| 100
| 0.58169
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,865
|
atbash_cipher.cpp
|
OpenGenus_cosmos/code/cryptography/src/atbash_cipher/atbash_cipher.cpp
|
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
//Atbash Cipher modified for English
string atbash(string s);
int main()
{
string s;
cout << "Enter message to encrypt/decrypt: ";
getline(cin, s);
cout << endl << atbash(s) << endl;
}
string atbash(string s)
{
string newstr = "";
for (size_t i = 0; i < s.length(); i++)
{
if (!isalpha(s[i]))
newstr += s[i];
else if (isupper(s[i]))
newstr += (char)('Z' - (s[i] - 'A'));
else
newstr += (char)('z' - (s[i] - 'a'));
}
return newstr;
}
| 609
|
C++
|
.cpp
| 27
| 17.888889
| 49
| 0.537133
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,870
|
autokey_cipher.cpp
|
OpenGenus_cosmos/code/cryptography/src/autokey_cipher/autokey_cipher.cpp
|
#include <iostream>
std::string autokeycipher(std::string text, char key, int encrypt)
{
for (int i = 0; i < text.length(); ++i)
{
if (isalpha(text[i]))
{
text[i] = toupper(text[i]);
}
}
int nextkey, keyvalue, result;
nextkey = toupper(key) - 'A';
for (int i = 0; i < text.length(); ++i)
{
if (isalpha(text[i]))
{
keyvalue = nextkey;
if (encrypt)
{
nextkey = text[i] - 'A';
text[i] = (text[i] - 'A' + keyvalue) % 26 + 'A';
}
else
{
result = (text[i] - 'A' - keyvalue) % 26 + 'A';
text[i] = result < 'A' ? (result + 26) : (result);
nextkey = text[i] - 'A';
}
}
}
return text;
}
int main(int argc, char **argv)
{
char key;
std::string plaintext;
std::cout << "Enter the Single Key word: ";
std::cin >> key;
std::cout << "Enter the Plain Text: ";
std::cin >> plaintext;
std::cout << std::endl
<< "The Plain Text is: " << plaintext;
/* 3rd argument decides whither to do 1-Encryption or 0-Decryption. */
std::string ciphertext = autokeycipher(plaintext, key, 1);
std::cout << std::endl
<< "The Text after Encryption(Cipher text) is: " << ciphertext;
std::string decryptedtext = autokeycipher(ciphertext, key, 0);
std::cout << std::endl
<< "After Decryption the Text is: " << decryptedtext;
return 0;
}
/*
Sample Input:
Enter the Single Key word: L //In A-Z, L will be at 11 index.
Enter the Plain Text: hello
Sample Output:
The Plain Text is: hello
The Text after Encryption(Cipher text) is: slpwz
After Decryption the Text is: hello
*/
| 1,799
|
C++
|
.cpp
| 60
| 22.883333
| 77
| 0.53619
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,872
|
columnar_transposition_cipher.cpp
|
OpenGenus_cosmos/code/cryptography/src/columnar_transposition_cipher/columnar_transposition_cipher.cpp
|
// CPP program for
// Columnar Transposition Cipher
#include <string>
#include <iostream>
#include <map>
using namespace std;
map<int, int> keyMap;
void setPermutationOrder(string key)
{
// Add the permutation
for (size_t i = 0; i < key.length(); i++)
keyMap[key[i]] = i;
}
// Encryption code for cipher
string encrypt(string object, string key)
{
int row, col, j;
string cipher = "";
/* calculate column of the matrix*/
col = key.length();
/* calculate Maximum row of the matrix*/
row = object.length() / col;
if (object.length() % col)
row += 1;
char matrix[row][col];
for (int i = 0, k = 0; i < row; i++)
for (int j = 0; j < col;)
{
if (object[k] == '\0')
{
/* Adding the padding character '_' */
matrix[i][j] = '_';
j++;
}
if (isalpha(object[k]) || object[k] == ' ')
{
/* Adding only space and alphabet into matrix*/
matrix[i][j] = object[k];
j++;
}
k++;
}
for (map<int, int>::iterator ii = keyMap.begin(); ii != keyMap.end(); ++ii)
{
j = ii->second;
// getting cipher text from matrix column wise using permuted key
for (int i = 0; i < row; i++)
if (isalpha(matrix[i][j]) || matrix[i][j] == ' ' || matrix[i][j] == '_')
cipher += matrix[i][j];
}
return cipher;
}
// Decryption code for cipher
string decrypt(string cipher, string key)
{
/* calculate row and column for cipher Matrix */
int col = key.length();
int row = cipher.length() / col;
char cipherMat[row][col];
/* add character into matrix column wise */
for (int j = 0, k = 0; j < col; j++)
for (int i = 0; i < row; i++)
cipherMat[i][j] = cipher[k++];
/* update the order of key for decryption */
int index = 0;
for (map<int, int>::iterator ii = keyMap.begin(); ii != keyMap.end(); ++ii)
ii->second = index++;
/* Arrange the matrix column wise according
* to permutation order by adding into new matrix */
char decCipher[row][col];
int k = 0;
for (int l = 0, j; key[l] != '\0'; k++)
{
j = keyMap[key[l++]];
for (int i = 0; i < row; i++)
decCipher[i][k] = cipherMat[i][j];
}
/* getting Message using matrix */
string msg = "";
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
if (decCipher[i][j] != '_')
msg += decCipher[i][j];
return msg;
}
// Driver Program for columnar transposition
int main()
{
/* message */
string msg = "defend the east wall of the castle";
string key = "GERMAN";
setPermutationOrder(key);
string cipher = encrypt(msg, key);
cout << "Encrypted Message: " << cipher << endl;
cout << "Decrypted Message: " << decrypt(cipher, key) << endl;
return 0;
}
| 3,008
|
C++
|
.cpp
| 97
| 24.216495
| 84
| 0.529453
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,873
|
test_push_relabel.cpp
|
OpenGenus_cosmos/code/graph_algorithms/test/push_relabel/test_push_relabel.cpp
|
#define CATCH_CONFIG_MAIN
#include "../../../../test/c++/catch.hpp"
#include "../../src/push_relabel/push_relabel.cpp"
#include <iostream>
int g_testCounter = 0;
std::vector<std::vector<int>> g_graph;
std::vector<std::vector<int>> g_flow;
int test(int s, int t, bool empty)
{
int k = (empty ? maxFlowEmpty(g_graph,s,t) : maxFlow(g_graph,g_flow,s,t));
g_graph.clear();
g_flow.clear();
return k;
}
TEST_CASE("push relabel max flow, zero initial flow")
{
g_graph.push_back(std::vector<int>{ 0, 1, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 1 });
g_graph.push_back(std::vector<int>{ 0, 0, 0 });
REQUIRE(test(0,2,true) == 1);
g_graph.push_back(std::vector<int>{ 0, 1, 0, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 1, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 0, 1 });
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0 });
REQUIRE(test(0,3,true) == 1);
g_graph.push_back(std::vector<int>{ 0, 10, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 5 });
g_graph.push_back(std::vector<int>{ 0, 0, 0 });
REQUIRE(test(0,2,true) == 5);
g_graph.push_back(std::vector<int>{ 0, 10, 10, 0, 0, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 10, 4, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 4, 4, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 12});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 8});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 0});
REQUIRE(test(0,5,true) == 18);
}
TEST_CASE("push relabel max flow, with existing flow")
{
g_graph.push_back(std::vector<int>{ 0, 10, 0 });
g_graph.push_back(std::vector<int>{ 0, 0, 5 });
g_graph.push_back(std::vector<int>{ 0, 0, 0 });
g_flow.push_back(std::vector<int>{ 0, 3, 0 });
g_flow.push_back(std::vector<int>{ 0, 0, 3 });
g_flow.push_back(std::vector<int>{ 0, 0, 0 });
REQUIRE(test(0,2,false) == 5);
// wikipedia example
g_graph.push_back(std::vector<int>{ 0, 15, 4, 0, 0, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 12, 0, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 10, 0});
g_graph.push_back(std::vector<int>{ 0, 0, 3, 0, 0, 7});
g_graph.push_back(std::vector<int>{ 0, 5, 0, 0, 0, 10});
g_graph.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 4, 0, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 4, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 0, 4, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 4});
g_flow.push_back(std::vector<int>{ 0, 4, 0, 0, 0, 0});
g_flow.push_back(std::vector<int>{ 0, 0, 0, 0, 0, 0});
REQUIRE(test(0,5,false) == 14);
}
| 2,714
|
C++
|
.cpp
| 61
| 40.098361
| 78
| 0.577685
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,876
|
travelling_salesman_dp.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/travelling_sales_man_dp/travelling_salesman_dp.cpp
|
#include <bits/stdc++.h>
using namespace std;
class brute_force
{
public:
int shortest_path_sum(int** edges_list, int num_nodes)
{
int source = 0;
vector<int> nodes;
for(int i=0;i<num_nodes;i++)
{
if(i != source)
{
nodes.push_back(i);
}
}
int n = nodes.size();
int shortest_path = INT_MAX;
while(next_permutation(nodes.begin(),nodes.end()))
{
int path_weight = 0;
int j = source;
for (int i = 0; i < n; i++)
{
path_weight += edges_list[j][nodes[i]];
j = nodes[i];
}
path_weight += edges_list[j][source];
shortest_path = min(shortest_path, path_weight);
}
return shortest_path;
}
};
class dynamic_programming
{
public:
int shortest_path_sum(int** edges_list,int** dp_array,int visited,int mask,int position,int num_nodes)
{
if(mask == visited)
{
return edges_list[position][0];
}
if(dp_array[mask][position] != -1)
{
return dp_array[mask][position];
}
int ans = INT_MAX;
for(int city=0;city<num_nodes;city++){
if((mask&(1<<city))==0){
int newAns = edges_list[position][city] + shortest_path_sum(edges_list,dp_array,visited,mask|(1<<city), city,num_nodes);
ans = min(ans, newAns);
}
}
dp_array[mask][position] = ans;
return dp_array[mask][position] = ans;
}
};
int main()
{
/// Getting the number of nodes and number of edges as input
int num_nodes,num_edges;
cin >> num_nodes >> num_edges;
/// creating a multi-dimensional array
int** edges_list = new int*[num_nodes];
for(int i=0;i<num_nodes;i++)
{
edges_list[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
edges_list[i][j] = 0;
}
}
/// adjacent matrix filling mechanism
for(int i=0;i<num_edges;i++)
{
int first_node,second_node,weight;
cin >> first_node >> second_node >> weight;
edges_list[first_node][second_node] = weight;
edges_list[second_node][first_node] = weight;
}
int visited = (1<<num_nodes)-1;
int m = 1<<num_nodes;
int** dp_array = new int*[m];
for(int i=0;i<m;i++)
{
dp_array[i] = new int[num_nodes];
for(int j=0;j<num_nodes;j++)
{
dp_array[i][j] = -1;
}
}
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout << edges_list[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
brute_force approach1;
dynamic_programming approach2;
cout << approach1.shortest_path_sum(edges_list,num_nodes) << endl;
cout << approach2.shortest_path_sum(edges_list,dp_array,visited,1,0,num_nodes) << endl;
return 0;
}
| 2,951
|
C++
|
.cpp
| 106
| 20.575472
| 123
| 0.535639
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,877
|
bipartite_checking2.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/bipartite_checking/bipartite_checking2.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
/* Part of Cosmos by OpenGenus Foundation */
bool dfs(int v, std::vector<std::vector<int>> &g, std::vector<int> &dp)
{
for (int u : g[v])
{
if (!dp[u])
{
dp[u] = 3 - dp[v]; // 3 - 1 = 2; 3 - 2 = 1
dfs(u, g, dp);
}
if (dp[u] != 3 - dp[v])
return false;
}
return true;
}
// Time complexity: O(|V| + |E|)
bool check_bipartite(std::vector<std::vector<int>> &g)
{
int n = (int) g.size();
std::vector<int> dp(n);
for (int i = 0; i < n; i++)
if (!dp[i])
{
dp[i] = 1;
if (!dfs(i, g, dp))
return false;
}
return true;
}
int main()
{
std::cout << "Enter the number of vertexes:" << std::endl;
int n;
std::cin >> n;
std::cout << "Enter the number of edges:" << std::endl;
int m;
std::cin >> m;
std::cout << "Enter the edges in the following format: u v. 0 <= u, v < n" << std::endl;
std::vector<std::vector<int>> g(n);
for (int i = 0; i < m; i++)
{
int u, v;
std::cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
if (check_bipartite(g))
std::cout << "This graph is bipartite.\n";
else
std::cout << "This graph is not bipartite.\n";
return 0;
}
| 1,376
|
C++
|
.cpp
| 55
| 18.963636
| 92
| 0.482838
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,878
|
bipartite_checking.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/bipartite_checking/bipartite_checking.cpp
|
#include <iostream>
#include <queue>
using namespace std;
int bipartite(int g[][10], int s, int n)
{
int *col = new int [n];
for (int i = 0; i < n; i++)
col[i] = -1;
queue<int> q;
col[s] = 1;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
if (g[u][u] == 1)
return 0;
for (int v = 0; v < n; v++)
{
if (g[u][v] && col[v] == -1)
{
col[v] = 1 - col[u];
q.push(v);
}
else if (g[u][v] == 1 && col[u] == col[v])
return 0;
}
}
return 1;
}
int main()
{
int g[10][10], n;
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> g[i][j];
int x = bipartite(g, 0, n);
cout << x << endl;
return 0;
}
| 875
|
C++
|
.cpp
| 41
| 14.02439
| 54
| 0.372405
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,880
|
kuhn_munkres_algorithm.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp
|
/*
* Part of Cosmos by OpenGenus Foundation
*
* Kuhn-Munkres algorithm: find the perfect matching in a balanced and weighted bipartite graph
* that gives the maximum sum of weights.
*/
#include <memory>
#include <vector>
#include <type_traits>
#include <limits>
#include <algorithm>
#include <iostream>
#include <initializer_list>
template
<
typename _WeightType,
typename = std::enable_if<
std::is_integral<_WeightType>::value && std::is_signed<_WeightType>::value>::type
>
class KuhnMunkresAlgorithm
{
public:
/*
* InputVector[i][j] contains the weight of the edge between Left node i and right node j.
* Let UpperLimit = std::numeric_limits<_WeightType>::max()/3 and LowerLimit = -UpperLimit,
* please make sure weights of edges are within range (LowerLimit, UpperLimit).
* If there is no edge between Left node i and right node j, set the weight to LowerLimit.
* At least one perfect matching must exist in the input bipartite graph.
*/
using InputType = std::vector<std::vector<_WeightType>>;
public:
explicit KuhnMunkresAlgorithm(const std::shared_ptr<InputType> Input) noexcept
: LeftsCount_(Input->size()),
RightsCount_((*Input)[0].size()),
leftsVisited_(LeftsCount_),
rightsVisited_(RightsCount_),
leftsLabel_(LeftsCount_),
rightsLabel_(RightsCount_),
Input_{Input}
{
}
/*
* Returns the perfect matching that gives the maximum sum of weights, represented by a vector.
* The index of the vector is the index of a right node. The element stored in the vector is the
* index of the Left node that is matched with the right node.
*/
std::vector<ptrdiff_t> run() noexcept
{
// Initialize the matching. At the beginning, no match exists in the matching.
std::vector<ptrdiff_t> matching(RightsCount_,
-1 /* -1 means this right node is unmatched. */);
// Initialize labels of Left nodes (labels of right nodes are already initialized to 0).
for (ptrdiff_t Left = 0; Left < LeftsCount_; ++Left)
{
_WeightType maxWeight = LowerLimit_;
for (ptrdiff_t right = 0; right < RightsCount_; ++right)
maxWeight = std::max(maxWeight, (*Input_)[Left][right]);
leftsLabel_[Left] = maxWeight;
}
for (ptrdiff_t Left = 0; Left < LeftsCount_; ++Left)
{
leftsVisited_.assign(LeftsCount_, false);
rightsVisited_.assign(RightsCount_, false);
diff_ = UpperLimit_;
while (!dfs(Left, matching)) // This loop won't exit until an augmenting path is found.
{
// Update labels.
for (ptrdiff_t i = 0; i < LeftsCount_; ++i)
if (leftsVisited_[i])
leftsLabel_[i] -= diff_;
for (ptrdiff_t j = 0; j < RightsCount_; ++j)
if (rightsVisited_[j])
rightsLabel_[j] += diff_;
leftsVisited_.assign(LeftsCount_, false);
rightsVisited_.assign(RightsCount_, false);
diff_ = UpperLimit_;
}
}
return matching;
}
private:
bool dfs(const ptrdiff_t Left, std::vector<ptrdiff_t> &matching) noexcept
{
leftsVisited_[Left] = true;
// Try to find an augmenting path.
for (ptrdiff_t right = 0; right < RightsCount_; ++right)
{
if (rightsVisited_[right])
continue; // Only an unvisited right node counts.
_WeightType t = leftsLabel_[Left] + rightsLabel_[right] - (*Input_)[Left][right];
if (t == 0) // In an equal subgraph.
{
rightsVisited_[right] = true;
if (matching[right] == -1 || dfs(matching[right], matching))
{
// Augmenting path found, update the matching.
matching[right] = Left;
return true;
}
}
else
diff_ = std::min(diff_, t);
}
return false;
}
private:
const ptrdiff_t LeftsCount_;
const ptrdiff_t RightsCount_;
_WeightType diff_ = UpperLimit_;
std::vector<bool> leftsVisited_;
std::vector<bool> rightsVisited_;
std::vector<_WeightType> leftsLabel_;
std::vector<_WeightType> rightsLabel_;
const std::shared_ptr<const InputType> Input_;
public:
static constexpr _WeightType UpperLimit_ = std::numeric_limits<_WeightType>::max() / 3;
static constexpr _WeightType LowerLimit_ = -UpperLimit_;
};
int main()
{
const int non = KuhnMunkresAlgorithm<int>::LowerLimit_;
const auto input = std::make_shared<KuhnMunkresAlgorithm<int>::InputType>(
std::initializer_list<std::vector<int>>{
{ 200, non, 180, 180, non, 190, non, 195 },
{ non, non, non, 170, 185, 186, 187, non },
{ non, 189, 170, 166, 160, non, non, 191 },
{ 160, 167, non, non, 200, 198, 195, 202 },
{ non, 170, 184, non, 202, 198, 169, 205 },
{ non, non, 187, 204, non, 185, 200, non },
{ 170, 170, 170, 170, 170, 170, 170, 170 },
{ non, 170, 169, 174, non, non, non, 197 }
});
KuhnMunkresAlgorithm<int> algorithm{input};
std::vector<ptrdiff_t> result = algorithm.run();
for (ptrdiff_t i = 0; i < result.size(); ++i)
std::cout << "right node " << i << " is matched with left node " << result[i] << ".\n";
std::cin.get();
return 0;
}
| 5,670
|
C++
|
.cpp
| 139
| 32.251799
| 100
| 0.582336
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,882
|
hamiltonian_path.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/hamiltonian_path/hamiltonian_path.cpp
|
#include <iostream>
#include <vector>
#include <bitset>
#include <cmath>
#include <cstdlib>
#include <cstring>
using namespace std;
const int MAXN = 8000;
const int INF = (int)1e9;
int n, m, *deg, *par, tl = -1;
bool *used;
vector <vector <int>> G;
inline void count_degs()
{
for (int i = 0; i < n; i++)
deg[i] = G[i].size();
}
bool DFS(int v, int p = -1)
{
tl = v;
used[v] = 1;
par[v] = p;
int gmin = INF;
int cnt = 1;
for (unsigned int i = 0; i < G[v].size(); i++)
deg[G[v][i]]--;
for (unsigned int i = 0; i < G[v].size(); i++)
if (!used[G[v][i]])
{
if (deg[G[v][i]] < gmin)
{
gmin = deg[G[v][i]];
cnt = 1;
}
else if (deg[G[v][i]] == gmin)
cnt++;
}
int num = rand() % cnt;
cnt = 0;
for (unsigned int i = 0; i < G[v].size(); i++)
if (!used[G[v][i]])
if (deg[G[v][i]] == gmin)
if (cnt++ == num)
return DFS(G[v][i], v);
return false;
}
int main()
{
cin >> n >> m;
deg = new int[n];
par = new int[n];
used = new bool[n];
G.resize(n);
for (int i = 0; i < m; i++)
{
int t1, t2;
cin >> t1 >> t2;
G[--t1].push_back(--t2);
G[t2].push_back(t1);
}
for (int iter = 0;; iter++)
{
tl = -1;
count_degs();
memset(used, 0, n * sizeof(used[0]));
memset(par, 0, n * sizeof(par[0]));
int vert = rand() % n;
DFS(vert);
bool flag = true;
for (int j = 0; j < n; j++)
if (!used[j])
flag = false;
if (flag)
{
for (int j = tl; j != -1; j = par[j])
cout << j + 1;
cout << "\n";
return 0;
}
}
}
| 1,861
|
C++
|
.cpp
| 81
| 15.901235
| 50
| 0.411964
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,885
|
transitive_closure_graph.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph.cpp
|
#include <stdio.h>
#include <iostream>
using namespace std;
void printSolution(int reach[][4])
{
cout << "Following matrix is transitive closure of the given graph\n";
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
cout << reach[i][j];
cout << endl;
}
}
void transitiveClosure(int graph[][4])
{
int reach[4][4], i, j, k;
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
reach[i][j] = graph[i][j];
for (k = 0; k < 4; k++)
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);
printSolution(reach);
}
int main()
{
int graph[4][4] = { {1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
transitiveClosure(graph);
}
| 883
|
C++
|
.cpp
| 34
| 19.029412
| 74
| 0.429752
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
9,889
|
dijkstra_shortest_path.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.cpp
|
#include <iostream>
#include <vector>
#include <set>
#include <utility>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
const int N = 1E4 + 1;
vector<pair<int, int>> graph[N];
set<pair<int, int>> pq;
int dist[N], vis[N];
int main()
{
int n, m; cin >> n >> m;
while (m--)
{
int u, v, w; cin >> u >> v >> w;
graph[u].push_back({v, w});
}
for (int i = 0; i <= n; i++)
dist[i] = 1E9, vis[i] = 0;
dist[1] = 0;
pq.insert({0, 1});
while (!pq.empty())
{
pair<int, int> p = *pq.begin();
pq.erase(pq.begin());
int u = p.second;
if (vis[u])
continue;
vis[u] = 1;
for (auto k : graph[u])
if (dist[k.first] > (dist[u] + k.second))
{
dist[k.first] = dist[u] + k.second;
pq.insert({dist[k.first], k.first});
}
}
for (int i = 2; i <= n; i++)
cout << dist[i] << " ";
return 0;
}
| 987
|
C++
|
.cpp
| 41
| 17.95122
| 53
| 0.466102
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,891
|
push_relabel.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/push_relabel/push_relabel.cpp
|
#include <vector>
#include <queue>
// push as much excess flow as possible from f to t
void push(std::vector<std::vector<int>> graph, std::vector<std::vector<int>>& flow,
std::vector<std::vector<int>>& residual, std::vector<int>& excess, int f, int t)
{
if (excess[f] <= 0)
{
std::cerr << "excess on node " << f << "is " << excess[f] << "\n";
return;
}
// calculate the maximum amount of flow that can be pushed
int tmp = std::min(excess[f], residual[f][t]);
excess[f] -= tmp;
excess[t] += tmp;
residual[f][t] -= tmp;
residual[t][f] += tmp;
// if this holdes, the edge is a backwards edge, so t->f will be reduced
if (graph[f][t] == 0)
{
flow[t][f] -= tmp;
return;
}
flow[f][t] += tmp;
}
// reset the height of node "node", so excess flow can be pushed
void relabel(std::vector<std::vector<int>> residual, std::vector<int>& height, int node)
{
int min = std::numeric_limits<int>::max();
for (int i = 0; i < residual.size(); ++i)
if (residual[node][i] > 0 && height[i] < min)
min = height[i];
height[node] = min + 1;
}
// expecting propper flow matrix, empty residual and no a ->b, b-> a capacities
int maxFlowResidual(std::vector<std::vector<int>> graph, std::vector<std::vector<int>>& flow,
std::vector<std::vector<int>>& residual, int s, int t)
{
int numNodes = graph.size();
// property check
if (graph.size() != graph[0].size() || graph.size() != flow.size())
std::cerr << "Graph matrix/Flow Matrix has wrong format\n";
std::vector<int> excess(numNodes, 0);
excess[s] = std::numeric_limits<int>::max();
// initialize the residual graph
for (int i = 0; i < numNodes; ++i)
{
for (int j = 0; j < numNodes; ++j)
{
int tmp = flow[i][j];
if (tmp > 0)
residual[j][i] = tmp;
int g = graph[i][j] - tmp;
if (g > 0)
residual[i][j] = g;
}
}
std::queue<int> activeNodes;
// push initial flow from source
for (int i = 0; i < numNodes; ++i)
{
if (graph[s][i] > 0 && graph[s][i] > flow[s][i])
{
push(graph, flow, residual, excess, s, i);
activeNodes.push(i);
}
}
// create initial height values
std::vector<int> height(numNodes, 0);
height[s] = numNodes;
height[t] = 0;
while (!activeNodes.empty())
{
int node = activeNodes.front();
// store all nodes that excess flow can be pushed to from 'node'
std::vector<int> nbrList;
for (int i = 0; i < numNodes; ++i)
{
if (residual[node][i] > 0)
nbrList.push_back(i);
}
int i = 0;
// apply push / relabel to 'node' until all excess flow is taken care of
while (excess[node] > 0)
{
if (i == nbrList.size())
{
/*
* all possible neighbors have been visited but there is still too much incoming
* flow so the height of 'node' has to be increased
*/
i=0;
relabel(residual, height, node);
}
else
{
int j = nbrList[i];
if (residual[node][j] > 0 && height[node] > height[j])
{
push(graph, flow, residual, excess, node, j);
if (excess[j] > 0 && j != s && j != t)
activeNodes.push(j);
}
++i;
}
}
activeNodes.pop();
}
// extract the flow
int res = 0;
for (int i = 0; i < numNodes; ++i)
res += std::max(0, flow[s][i]);
return res;
}
int maxFlow(std::vector<std::vector<int>> graph,
std::vector<std::vector<int>>& flow, int s, int t)
{
int l = graph.size();
std::vector<std::vector<int>> emptyResidual(l, std::vector<int>(l, 0));
return maxFlowResidual(graph, flow, emptyResidual, s, t);
}
int maxFlowEmpty(std::vector<std::vector<int>> graph, int s, int t)
{
// create empty flow matrix
int l = graph.size();
std::vector<std::vector<int>> emptyFlow(l, std::vector<int>(l, 0));
return maxFlow(graph, emptyFlow, s, t);
}
| 4,385
|
C++
|
.cpp
| 128
| 25.851563
| 97
| 0.523855
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,893
|
topological_sort.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/topological_sort/topological_sort.cpp
|
/* Part of Cosmos by OpenGenus Foundation */
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define NUM_V 100005
vector<int> adjList[NUM_V + 5];
int inDegree[NUM_V + 5];
int vertex;
vector<int> toposort()
{
vector<int> result;
queue<int> q;
for (int i = 1; i <= vertex; i++)
// if no incoming degree, add to queue
if (inDegree[i] == 0)
q.push(i);
while (!q.empty())
{
int front = q.front();
q.pop();
// add into toposort result
result.push_back(front);
for (size_t i = 0; i < adjList[front].size(); i++)
{
int neighbor = adjList[front][i];
inDegree[neighbor]--;
// if already no incoming degree, then ready to put in toposort list
if (inDegree[neighbor] == 0)
q.push(neighbor);
}
}
return result;
}
int main()
{
/* consider following graph
* 1----->2----->5
* | ^^
* | / |
* | / |
* | / |
* v / |
* 4----->3
* one of the solution would be
* 1 -> 4 -> 3 -> 2 -> 5
*/
vertex = 5;
adjList[1].push_back(2);
adjList[1].push_back(4);
adjList[2].push_back(5);
adjList[3].push_back(2);
adjList[4].push_back(2);
adjList[4].push_back(3);
inDegree[1] = 0;
inDegree[2] = 3;
inDegree[3] = 1;
inDegree[4] = 1;
inDegree[5] = 1;
vector<int> toposortResult = toposort();
printf("toposort :");
for (size_t i = 0; i < toposortResult.size(); i++)
printf(" %d", toposortResult[i]);
printf("\n");
}
| 1,678
|
C++
|
.cpp
| 67
| 19.283582
| 80
| 0.528231
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,894
|
kahn_algorithm_basic.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/topological_sort/kahn_algorithm_basic.cpp
|
/*
* Implementation of the Kahn's algorithm
* for topological sort in a directed acyclic graph
*/
#include <iostream>
#include "bits/stdc++.h"
using namespace std;
queue<int> q, q2;
long long n = 100000;
int v, e, v1, v2, visited[10000], level[100000], indegree[100000];
vector<int> g[100000];
void bfs(int i)
{
while (!q.empty())
{
for (int j = 0; j < g[q.front()].size(); j++)
{
indegree[g[q.front()][j]]--;
}
for (int j = 0; j < g[q.front()].size(); j++)
{
if (visited[g[q.front()][j]] != 1)
{
if (indegree[g[q.front()][j]] == 0)
{
q.push(g[q.front()][j]);
visited[g[q.front()][j]] = 1;
}
}
}
cout << q.front() << " ";
q.pop();
}
}
int main()
{
int v, e, v1, v2;
cin >> v >> e;
g[v + 1].resize(v + 1);
for (int i = 0; i < e; i++)
{
cin >> v1 >> v2;
g[v1].push_back(v2);
indegree[v2]++;
}
cout << "Nodes and indegrees\n";
for (int i = 1; i <= v; i++)
{
cout << i << " " << indegree[i] << endl;
}
cout << "Topological sort order :";
for (int i = 1; i < v + 1; i++)
if (indegree[i] == 0)
{
q.push(i);
visited[i] = 1;
}
bfs(1);
cout << endl;
}
| 1,229
|
C++
|
.cpp
| 60
| 16.383333
| 66
| 0.491789
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,895
|
kahn_algo_unique_toposort.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/topological_sort/kahn_algo_unique_toposort.cpp
|
// Sample problem for using this algorithm - UVA 11060 Beverages
#include <bits/stdc++.h>
#define all(a) a.begin(), a.end()
#define ll long long
#define inp(a) scanf("%d", &a)
#define out(a) printf("%d\n", a)
#define inp2(a) scanf("%lld", &a)
#define out2(a) printf("%lld\n", a)
#define arrinput(a, n) for (int i = 0; i < n; i++) scanf("%d", &a[i]);
#define pii pair<int, int>
#define piii pair<int, pair<int, int>>
#define vi vector<int>
#define rep(i, start, n) for (size_t i = start; i < static_cast<size_t>(n); i++)
#define pb push_back
#define F first
#define S second
#define mp make_pair
#define vb vector<bool>
#define testcases() int test; scanf("%d", &test); while (test--)
#define priorityqueue priority_queue<int, vector<int>, greater<int>>
#define minheappop(a) pop_heap(a.begin(), a.end(), compare); a.pop_back();
#define maxheappop(a) pop_heap(a.begin(), a.end()); a.pop_back();
#define minheappush(a, b) a.push_back(b); push_heap(a.begin(), a.end(), compare);
#define maxheappush(a, b) a.push_back(b); push_heap(a.begin(), a.end());
const int mod = 1000000007;
using namespace std;
map<string, vector<string>> graph;
map<string, int> inDegree;
vector<string> alcohols;
int n, m;
string u, v;
void kahnalgo()
{
set< pair<int, string >> q;
rep(i, 0, alcohols.size()) {
if (inDegree[alcohols[i]] == 0)
{
q.insert(mp(i, alcohols[i]));
inDegree[alcohols[i]] = -1;
}
}
while (q.size())
{
pair<int, string> cc = *q.begin();
string c = cc.S;
cout << " " << c;
q.erase(q.begin());
rep(i, 0, graph[c].size()) {
inDegree[graph[c][i]] -= 1;
}
rep(i, 0, alcohols.size()) {
if (inDegree[alcohols[i]] == 0)
{
q.insert(mp(i, alcohols[i]));
inDegree[alcohols[i]] = -1;
}
}
}
}
int main()
{
int cases = 0;
while (inp(n) != EOF)
{
cases += 1;
inDegree.clear();
graph.clear();
alcohols.clear();
rep(i, 0, n) {
cin >> u;
alcohols.pb(u);
graph[u] = vector<string>();
}
inp(m);
rep(i, 0, m) {
cin >> u >> v;
inDegree[v] += 1;
graph[u].pb(v);
}
printf("Case #%d: Dilbert should drink beverages in this order:", cases);
kahnalgo();
printf(".\n\n");
getchar();
}
return 0;
}
| 2,478
|
C++
|
.cpp
| 86
| 23.011628
| 81
| 0.543287
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,902
|
centroid_decomposition.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/centroid_decomposition/centroid_decomposition.cpp
|
#include <iostream>
#include <vector>
class Graph
{
public:
int ver_;
std::vector<std::vector<int>> adj_;
std::vector<std::vector<int>> centroidTree_;
std::vector<int> sizes_;
std::vector<bool> marked_;
Graph(int num) :
ver_(num),
adj_(num + 1),
centroidTree_(num + 1),
sizes_(num + 1),
marked_(num + 1)
{
}
void addEdge(int x, int y, std::vector<std::vector<int>> &graph);
void calcSizes(int cur, int par, std::vector<std::vector<int>> graph);
int findCentroid(int cur, int par, int vertices, std::vector<std::vector<int>> graph);
void decomposeTree(int cur, int par, int total, int level,
std::vector<std::vector<int>> &Level);
};
void Graph::addEdge(int x, int y, std::vector<std::vector<int>> &graph)
{
if (x < 0 || x > ver_)
{
throw std::out_of_range{"x is out of boundaries"};
}
if (y < 0 || y > ver_)
{
throw std::out_of_range{"y is out of boundaries"};
}
graph[x].push_back(y);
graph[y].push_back(x);
}
void Graph::calcSizes(int cur, int par, std::vector<std::vector<int>> graph)
{
sizes_[cur] = 1;
for (const auto& to : graph[cur])
if (!(to == par || marked_[to]))
{
calcSizes (to, cur, graph);
sizes_[cur] += sizes_[to];
}
}
int Graph::findCentroid(int cur, int par, int vertices, std::vector<std::vector<int>> graph)
{
for (const auto& to : graph[cur])
if (!(to == par || marked_[to]))
if (sizes_[to] > vertices / 2)
return findCentroid(to, cur, vertices, graph);
return cur;
}
void Graph::decomposeTree(int cur, int par, int total, int level,
std::vector<std::vector<int>> &Level)
{
calcSizes(cur, -1, adj_);
int centroid = findCentroid(cur, -1, sizes_[cur], adj_);
Level[level].push_back(centroid);
calcSizes(centroid, -1, adj_);
marked_[centroid] = true;
for (const auto& to : adj_[centroid])
if (!(to == par || marked_[to]))
{
decomposeTree(to, cur, sizes_[to], level + 1, Level);
addEdge(cur, to, centroidTree_);
}
}
void showOutput(std::vector<std::vector<int>> Level)
{
for (int i = 1; Level[i].empty() == false; ++i)
{
std::cout << "Centroids of level " << i << ": ";
bool more_than_1 = false;
for (const auto& j : Level[i])
{
if (more_than_1 == true)
std::cout << ", ";
std::cout << j;
more_than_1 = true;
}
std::cout << '\n';
}
}
int main()
{
std::vector<std::vector<int>> Level(8);
Graph tree(7);
tree.addEdge(1, 2, tree.adj_);
tree.addEdge(1, 3, tree.adj_);
tree.addEdge(2, 4, tree.adj_);
tree.addEdge(4, 5, tree.adj_);
tree.addEdge(4, 6, tree.adj_);
tree.addEdge(2, 7, tree.adj_);
tree.decomposeTree(1, -1, tree.ver_, 1, Level);
showOutput(Level);
return 0;
}
| 3,006
|
C++
|
.cpp
| 100
| 23.84
| 92
| 0.550915
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,904
|
cut_vertices.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/cut_vertices/cut_vertices.cpp
|
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
typedef long long ll;
// Part of Cosmos by OpenGenus Foundation
const int MAXN = 1e4 + 5;
vector<int> adj[MAXN];
bool vis[MAXN], AP[MAXN];
int n, m, currTime, disc[MAXN];
int low[MAXN]; // low[i] is the minimum of visited currTime of all vertices which are reachable from i.
void init()
{
currTime = 0;
for (int i = 1; i <= n; i++)
{
adj[i].clear(); vis[i] = false; AP[i] = false; disc[i] = 0; low[i] = INT_MAX;
}
}
void dfs(int u, int parent)
{
vis[u] = true;
disc[u] = low[u] = currTime + 1;
int child = 0;
for (auto v : adj[u])
{
if (v == parent)
continue;
if (!vis[v])
{
child = child + 1;
currTime++;
dfs(v, u);
//check if subtree rooted at v has a connection to one of the ancestors of u.
low[u] = min(low[u], low[v]);
if (parent == -1 && child > 1)
AP[u] = true;
if (parent != -1 && low[v] >= disc[u])
AP[u] = true;
}
else
// back edge.
low[u] = min(low[u], disc[v]);
}
}
int main()
{
cin >> n >> m; // n = number of vertices, m = number of edges
init();
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1, -1); //start from any random vertex, make its parent -1.
return 0;
}
| 1,523
|
C++
|
.cpp
| 59
| 19.627119
| 104
| 0.503429
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,906
|
boruvka_minimum_spanning_tree.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/boruvka_minimum_spanning_tree/boruvka_minimum_spanning_tree.cpp
|
#include <iostream>
#include <vector>
const int MAXN = 10000;
const int inf = 0x3fffffff;
int nodeCount, edgesCount;
std::vector<std::pair<int, int>> graf[MAXN];
void readGraph()
{
std::cin >> nodeCount >> edgesCount;
for (int i = 0; i < edgesCount; i++)
{
int x, y, w;
std::cin >> x >> y >> w;
graf[x].push_back({y, w});
graf[y].push_back({x, w});
}
}
int parent[MAXN], rank[MAXN];
// Initialize the forest of trees
void initDisjoint()
{
for (int i = 0; i < nodeCount; i++)
{
parent[i] = i;
rank[i] = 0;
}
}
// Get set representative
int getSR(int x)
{
if (x == parent[x])
return x;
return parent[x] = getSR(parent[x]);
}
int areUnited(int x, int y)
{
return getSR(x) == getSR(y);
}
void unite(int x, int y)
{
x = getSR(x);
y = getSR(y);
if (rank[x] > rank[y])
parent[y] = x;
else
{
parent[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
std::pair<int, int> cheapEdge[MAXN];
int solve()
{
int numberOfTrees = nodeCount;
int weightSum = 0;
initDisjoint();
while (numberOfTrees > 1)
{
// initializing cheapest edge to "none"
for (int i = 0; i < nodeCount; i++)
cheapEdge[i].first = -1;
for (int i = 0; i < nodeCount; i++)
for (size_t j = 0; j < graf[i].size(); j++)
{
std::pair<int, int> edge = graf[i][j];
int xsr = getSR(i);
int ysr = getSR(edge.first);
int w = edge.second;
if (xsr == ysr)
continue;
if (cheapEdge[xsr].first == -1 ||
w < graf[cheapEdge[xsr].first][cheapEdge[xsr].second].second)
cheapEdge[xsr] = {i, j};
if (cheapEdge[ysr].first == -1 ||
w < graf[cheapEdge[ysr].first][cheapEdge[ysr].second].second)
cheapEdge[ysr] = {i, j};
}
for (int i = 0; i < nodeCount; i++)
{
int xsr = getSR(i);
if (cheapEdge[xsr].first == -1)
continue;
std::pair<int, int> edge = graf[cheapEdge[xsr].first][cheapEdge[xsr].second];
int ysr = getSR(edge.first);
if (xsr == ysr)
continue;
weightSum += edge.second;
unite(xsr, ysr);
numberOfTrees--;
}
}
return weightSum;
}
int main()
{
readGraph();
int weight = solve();
std::cout << "The weight of the minimum spanning tree is " << weight;
return 0;
}
| 2,639
|
C++
|
.cpp
| 101
| 18.722772
| 89
| 0.497032
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
9,910
|
count_of_ways_n.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/count_of_ways_n/count_of_ways_n.cpp
|
#include <iostream>
#include <vector>
const int MOD = 1000000007;
int size, n;
std::vector< std::vector<long long>> multiple (std::vector< std::vector<long long>> a,
std::vector< std::vector<long long>> b)
{
std::vector< std::vector<long long>> res(size);
for (int i = 0; i < size; i++)
res[i].resize(size);
for (int i = 0; i < size; i++)
for (int l = 0; l < size; l++)
{
long long tmp = 0;
for (int j = 0; j < size; j++)
tmp = (tmp + a[i][j] * b[j][l]) % MOD;
res[i][l] = tmp;
}
return res;
}
std::vector< std::vector<long long>> binPow(std::vector< std::vector<long long>> a, long long power)
{
std::vector< std::vector<long long>> ans(size);
for (int i = 0; i < size; i++)
{
ans[i].resize(size);
ans[i][i] = 1;
}
std::vector< std::vector<long long>> cur = a;
while (power)
{
if (power & 1)
ans = multiple (ans, cur);
cur = multiple (cur, cur);
power /= 2;
}
return ans;
}
int main ()
{
std::cin >> size >> n;
int from, to;
std::cin >> from >> to;
std::vector< std::vector<long long>> graph(size);
for (int i = 0; i < size; i++)
graph[i].resize(size);
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
std::cin >> graph[i][j];
std::cout << binPow(graph, n)[from][to];
}
| 1,495
|
C++
|
.cpp
| 51
| 22.215686
| 100
| 0.490169
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,912
|
lowest_common_ancestor.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/lowest_common_ancestor/lowest_common_ancestor.cpp
|
#include <iostream>
#include <vector>
#include <array>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Problem Statement
/*
* Given a tree with n nodes
* Your task is to process q queries of the following form:
* who is the lowest common ancestor of nodes a and b in the tree?
*
* The lowest common ancestor of two nodes of a rooted tree is the lowest node
* whose subtree contains both the nodes.
*/
void dfs(int k, int p, vector<int> &depth, vector<vector<int>> &adj, vector<array<int, 20>> &ancestor)
{
ancestor[k][0] = p;
depth[k] = depth[p] + 1;
for (int i = 1; i < 20; i++)
ancestor[k][i] = ancestor[ancestor[k][i - 1]][i - 1];
for (int i : adj[k])
if (i != p)
dfs(i, k, depth, adj, ancestor);
}
int kthAncestor(int k, int x, vector<array<int, 20>> &ancestor)
{
for (int i = 0; i < 20; i++)
if (x & (1 << i))
k = ancestor[k][i];
return k;
}
int lca(int a, int b, vector<array<int, 20>> &ancestor, vector<int> &depth)
{
if (depth[a] < depth[b])
swap(a, b);
a = kthAncestor(a, depth[a] - depth[b], ancestor);
if (a == b)
return b;
for (int i = 19; i >= 0; i--)
if (ancestor[a][i] != ancestor[b][i])
a = ancestor[a][i], b = ancestor[b][i];
return ancestor[a][0];
}
int main()
{
int n;
cin >> n;
vector<vector<int>> adj(n + 1);
for (int i = 1; i < n; i++)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<int> depth(n + 1);
vector<array<int, 20>> ancestor(n + 1);
dfs(1, 0, depth, adj, ancestor);
int q;
cin >> q;
while (q--)
{
int a, b;
cin >> a >> b;
cout << lca(a, b, ancestor, depth) << '\n';
}
}
| 1,812
|
C++
|
.cpp
| 67
| 22.134328
| 102
| 0.547977
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
9,913
|
cycle_undirected_graph_union_find.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/cycle_undirected_graph/cycle_undirected_graph_union_find.cpp
|
/*this includes code for cheking the cycle is undirected graph using unionfind disjoint data structure
*
* the implementation is very fast
* as it implements unionfind disjoint structure using path-compression and rank heuristics
*/
#include <vector>
#include <cstddef>
int p[1000000]; //stores parent
int rnk[1000000];
int findset(int u) //find set representative of u
{
if (u == p[u])
return u;
return p[u] = findset(p[u]);
}
void unionset(int i, int j) //merge sets with elements i and j
{
int a = findset(i);
int b = findset(j);
if (a != b)
{
if (rnk[a] > rnk[b])
p[b] = a;
else
p[a] = b;
if (rnk[a] == rnk[b])
++rnk[b];
}
}
//note that edgelist can be formed using graph input itself
bool detectcycle(std::vector<std::pair<int, int>> edgelist) // graph given in edge list representation
{
for (std::size_t i = 0; i < edgelist.size(); ++i)
{
std::pair<int, int> u = edgelist[i];
int a = u.first;
int b = u.second;
if (findset(a) == findset(b))
return true;
else
unionset(a, b);
}
return false;
}
| 1,188
|
C++
|
.cpp
| 44
| 21.795455
| 102
| 0.596137
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,915
|
breadth_first_search.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/breadth_first_search/breadth_first_search.cpp
|
#include <iostream>
#include <map>
#include <set>
#include <queue>
/* Part of Cosmos by OpenGenus Foundation */
void bfs(int start, // the node that we are currently at
std::map<int, std::set<int>>& adjList, // the adjacency list for each node
std::map<int, bool>& visited, // the 'visited' state for each node
std::map<int, int>& distance // the distance from the `start` node
)
{
// First, clear the distance map, so that only nodes that we can actually reach from the `start` appear in it at the end
distance.clear();
// This queue will hold pairs of numbers of the form (nodeNumber, distance)
std::queue<std::pair<int, int>> Q;
// Add the first node with distance 0 to the queue and mark it as visited
Q.push(std::make_pair(start, 0));
visited[start] = true;
// Repeat the algorithm until there are no more nodes left to process
while (!Q.empty())
{
// Take the node from the front of the queue and pop it off the queue
auto entry = Q.front(); Q.pop();
int node = entry.first;
int dist = entry.second;
// Put the distance to this node into the distance map (this is the minimal distance to this node)
distance[node] = dist;
// Iterate over the neighbours of the current node
for (auto neighbour : adjList[node])
if (!visited[neighbour])
{
// Mark the neighbour node as visited
visited[neighbour] = true;
Q.push(std::make_pair(neighbour, dist + 1));
}
}
}
void addEdge(int a, int b, std::map<int, std::set<int>>& adjList)
{
adjList[a].insert(b);
adjList[b].insert(a);
}
int main()
{
/*
* Do a breadth-first search in this graph:
*
* 1--2--4--7
| / \ |
|/ \ |
| 3 5--6
|
| 8--9
*/
std::map<int, std::set<int>> adjList;
std::map<int, bool> visited;
std::map<int, int> dist;
addEdge(1, 2, adjList);
addEdge(1, 3, adjList);
addEdge(2, 3, adjList);
addEdge(2, 4, adjList);
addEdge(2, 5, adjList);
addEdge(4, 7, adjList);
addEdge(5, 6, adjList);
addEdge(6, 7, adjList);
addEdge(8, 9, adjList);
// Set all nodes as unvisited at first
for (int i = 1; i <= 8; i++)
visited[i] = false;
// Perform a bfs from the node `1`
bfs(1, adjList, visited, dist);
// Print the distance to all visited nodes
for (auto entry : dist)
std::cout << "Distance from 1 to " << entry.first << " is " << entry.second << std::endl;
return 0;
}
| 2,733
|
C++
|
.cpp
| 76
| 29.855263
| 124
| 0.569161
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,917
|
redundant_connection.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/redundant-connection/redundant_connection.cpp
|
/*
* Part of Cosmos by OpenGenus foundation
*
* Redundant Connection
*
* Description
*
* Return an edge that can be removed from an undirected graph so that the resulting graph is a tree of N nodes
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> parent; //disjoint set;
int findParent(int a)
{
if (parent[a] != a)
return parent[a] = findParent(parent[a]);
else
return a;
}
vector<int> findRedundantConnection(vector<vector<int>>& edges)
{
int n = edges.size();
parent.resize(n+1,0);
for(int i=0;i<=n;i++)
{
parent[i] = i;
}
vector<int> ans(2,0); //storing the answer
for(int i=0;i<n;i++)
{
int x = findParent(edges[i][0]); //Union Set
int y = findParent(edges[i][1]);
if(x != y)
parent[y] = x;
else
{
ans[0] = edges[i][0];
ans[1] = edges[i][1];
}
}
return ans;
}
int main ()
{
vector<vector<int>> edges;
int n , e;
cin >> n >> e;
cout << "Input number of vertices" << endl;
cout << "Input number of edges" << endl;
for(int i=0;i<e;i++)
{
int u , v; //temporary variables
vector<int> edge(2); //single edge
cin >> u >> v;
edge[0] = u;
edge[1] = v;
edges[i].push_back(edge);
}
cout << findRedundantConnection(edges);
return 0;
}
| 1,450
|
C++
|
.cpp
| 63
| 17.825397
| 111
| 0.554269
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,921
|
depth_first_search.cpp
|
OpenGenus_cosmos/code/graph_algorithms/src/depth_first_search/depth_first_search.cpp
|
#include <iostream>
#include <map>
#include <set>
/* Part of Cosmos by OpenGenus Foundation */
void dfs(int current, // the node that we are currently at
std::map<int, std::set<int>>& adjList, // the adjacency list for each node
std::map<int, bool>& visited) // the 'visited' state for each node
{
if (visited[current])
return;
visited[current] = true;
for (auto neighbour : adjList[current])
dfs(neighbour, adjList, visited);
}
void addEdge(int a, int b, std::map<int, std::set<int>>& adjList)
{
adjList[a].insert(b);
adjList[b].insert(a);
}
int main()
{
/*
* Do a depth-first search in this graph:
*
* 1--2--4
| /
|/
| 3
|
| 5--6--7
|
| 8
*/
std::map<int, std::set<int>> adjList;
std::map<int, bool> visited;
addEdge(1, 2, adjList);
addEdge(1, 3, adjList);
addEdge(2, 3, adjList);
addEdge(2, 4, adjList);
addEdge(5, 6, adjList);
addEdge(6, 7, adjList);
addEdge(6, 8, adjList);
// Set all nodes as unvisited at first
for (int i = 1; i <= 8; i++)
visited[i] = false;
// Perform a dfs from the node `1`
dfs(1, adjList, visited);
// Print all the visited nodes:
for (int i = 1; i <= 8; i++)
if (visited[i])
std::cout << i << " ";
return 0;
}
| 1,435
|
C++
|
.cpp
| 53
| 22.075472
| 108
| 0.534545
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,922
|
test_kruskal.cpp
|
OpenGenus_cosmos/code/greedy_algorithms/test/kruskal_minimum_spanning_tree/test_kruskal.cpp
|
#include "../../src/kruskal_minimum_spanning_tree/kruskal.cpp"
#include "../../../data_structures/src/tree/multiway_tree/union_find/union_find_dynamic.cpp"
#include <iostream>
using namespace std;
pair<int, int> edgeFunc(pair<pair<int, int>, int> edge)
{
return edge.first;
}
class HeapCompare
{
public:
bool operator()(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b)
{
return a.second > b.second;
}
};
int main()
{
using namespace std;
vector<int> vec{1, 2, 3, 4, 5, 6, 7};
/*
* 1---(12)----2
* / / \
* / / \
* (35) (25) (24)
* / / \
* / / \
* 6 7 3
\ /\ /
\ / \ /
\ (15) (18) (22) (32)
\ / \ /
\/ \ /
\ 5---(10)----4
*/
vector<pair<pair<int, int>, int>> edge_weight{{{1, 2}, 12},
{{2, 3}, 24},
{{3, 4}, 32},
{{4, 5}, 10},
{{5, 6}, 15},
{{6, 1}, 35},
{{2, 7}, 25},
{{4, 7}, 22},
{{5, 7}, 18}};
make_heap(edge_weight.begin(), edge_weight.end(), HeapCompare());
auto res = kruskal(vec.size() - 1,
edge_weight,
HeapCompare(),
edgeFunc, UnionFind<int>());
// print
auto it = res.begin();
while (it != res.end())
{
cout << it->first.first << "\t" << it->first.second << endl;
++it;
}
/*
* 1---(12)----2
* / \
* / \
* (25) (24)
* / \
* / \
* 6 7 3
\ /
\ /
\ (15) (18)
\ /
\/
\ 5---(10)----4
*/
return 0;
}
| 2,173
|
C++
|
.cpp
| 73
| 19.041096
| 92
| 0.301769
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,924
|
SplitArrayLargestSum.cpp
|
OpenGenus_cosmos/code/greedy_algorithms/src/SplitArrayLargestSum/SplitArrayLargestSum.cpp
|
//CODE
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
/*
Parameters:
nums - The input array;
cuts - How many cuts are available (cuts = #groups - 1);
max - The maximum of the (sum of elements in one group);
Return:
Whether we can use at most 'cuts' number of cuts to segment the entire array,
such that the sum of each group will not exceed 'max'.
*/
bool doable (const vector<int>& nums, int cuts, long long max) {
// 'acc' is the temporary accumulator for the currently processed group.
int acc = 0;
for (int num : nums) {
// If the current processed element in this array is larger than 'max', we cannot segment the array.
// (Reason is straightforward, if 'nums' is [10, 2, 3, 5] and 'max' is 6, even you can have 3 cuts
// (by which you can cut array as [[10], [2], [3], [5]]), the group containing 10 will be larger than 6,
// there is no way to do this).
// Ps: This step is unnecessary in this solution. Because 'left' in the splitArray() function can assure
// 'max' will be larger than every single element. I just want to write a generalized doable() function :)
if (num > max) return false;
// If the (sum of the currently processed group) + (current element) is smaller than max, we can add current
// element into this group.
else if (acc + num <= max) acc += num;
// If not, we will make a cut before this element, and this element will be the first element in the new group.
else {
--cuts;
acc = num;
// If we've used up all cuts, this means this 'max' is not doable.
if (cuts < 0) return false;
}
}
// If we can reach here, this means we've used at most 'cuts' cut to segment the array, and the sum of each groups is
// not larger than 'max'. Yeah!
return true;
}
public:
int splitArray(vector<int>& nums, int m) {
// Use long long to avoid overflow.
long long left = 0, right = 0;
// The smallest possible value ('left') is the the value of the largest element in this array.
// The largest possible value ('right') is the sum of all elements in this array.
for (int num : nums) {
left = max(left, (long long)num);
right += num;
}
// Use binary search, find the lower bound of the possible (minimum sum of groups within m - 1 cuts).
while (left < right) {
long long mid = left + (right - left) / 2;
if (doable(nums, m - 1, mid)) right = mid;
else left = mid + 1;
}
return left;
}
};
// Driver Code Starts.
int main()
{
int t;
cout << "Inpur the number of Test cases :";
cin >> t;
while (t--)
{
int n,m;
cout << "Enter the Quantity of Array Elements: ";
cin >> n;
cout << "Input " << n << " Array elements: ";
vector<int> nums(n);
for (auto &it : nums) {
cin >> it;
}
cout << "Enter the value of m: ";
cin >> m;
Solution ob;
cout << "The largest sum among the " << m << " subarray is " << ob.splitArray(nums, m) << endl;
}
return 0;
}
| 3,569
|
C++
|
.cpp
| 82
| 32.878049
| 125
| 0.560335
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,925
|
kruskal.cpp
|
OpenGenus_cosmos/code/greedy_algorithms/src/kruskal_minimum_spanning_tree/kruskal.cpp
|
#include <algorithm>
#include <vector>
namespace kruskal_impl {
using namespace std;
template<typename _ForwardIter, typename _ValueType>
pair<_ValueType, _ValueType> edgeFuncPolicy(_ForwardIter it);
template<typename _ValueType>
struct UnionFindPolicy
{
void merge(_ValueType a, _ValueType b);
bool connected(_ValueType a, _ValueType b);
};
} // kruskal_impl
template<typename _HeapedContainer,
typename _HeapCompare,
typename _EdgeFunc,
typename _UnionFind>
std::vector<typename _HeapedContainer::value_type>
kruskal(const size_t minimum_edge_count,
_HeapedContainer edges,
_HeapCompare compare,
_EdgeFunc ef,
_UnionFind union_sets)
{
using namespace std;
using value_type = typename _HeapedContainer::value_type;
auto min_spanning_tree = vector<value_type>{};
while (min_spanning_tree.size() < minimum_edge_count && !edges.empty())
{
// the pick elem is on the back
pop_heap(edges.begin(), edges.end(), compare);
auto edge = ef(edges.back());
// cycle detection
if (!union_sets.connected(edge.first, edge.second))
{
union_sets.merge(edge.first, edge.second);
min_spanning_tree.push_back(edges.back());
}
edges.pop_back();
}
return min_spanning_tree;
}
| 1,348
|
C++
|
.cpp
| 42
| 26.5
| 75
| 0.67284
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,932
|
min_operation.cpp
|
OpenGenus_cosmos/code/greedy_algorithms/src/min_operation_to_make_gcd_k/min_operation.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n; // no. of elements in array
int k; // new GCD
cout << "Enter number of elements in array: ";
cin >> n;
cout << "\nEnter the array: ";
int arr[n]; // array
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
cout << "\nEnter value of k: ";
cin >> k;
if(k == 0)
{
cout << "\nInvalid value for gcd";
return 0;
}
sort(arr, arr + n);
int min_operation = 0;
for(int i = 1 ; i < n ; i++)
min_operation += min(arr[i] % k, k - (arr[i] % k));
//shift towards closest multiple
if(arr[0] > k)
min_operation += arr[0] - k;
else
min_operation += k - arr[0];
cout << "\nMinimum Number of Operations: " << min_operation;
return 0;
}
| 895
|
C++
|
.cpp
| 31
| 20.774194
| 68
| 0.460648
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
9,939
|
partitions_of_set.cpp
|
OpenGenus_cosmos/code/backtracking/src/partitions_of_set/partitions_of_set.cpp
|
/// Part of Cosmos by OpenGenus Foundation
#include <stdio.h>
#include <vector>
void backtrack(int level);
void print_sol();
std::vector<int> v;
std::vector<int> solution;
int maxfromSol = 0;
int N;
int solsFound = 0;
int main()
{
scanf("%d", &N);
v.reserve(N + 1);
solution.reserve(N + 1);
for (int i = 1; i <= N; i++)
scanf("%d", &v[i]);
backtrack(1);
return 0;
}
void backtrack(int level)
{
if (level == N + 1)
print_sol();
else
{
for (int i = 1; i <= maxfromSol; i++)
{
solution[level] = i;
backtrack(level + 1);
}
solution[level] = maxfromSol + 1;
maxfromSol++;
backtrack(level + 1);
maxfromSol--;
}
}
void print_sol()
{
printf("SOLUTION %d\n", ++solsFound);
for (int i = 1; i <= maxfromSol; i++)
{
printf("Partition %d:", i);
for (int j = 1; j <= N; j++)
if (solution[j] == i)
printf("%d ", v[j]);
printf("\n");
}
}
| 1,027
|
C++
|
.cpp
| 49
| 15.77551
| 45
| 0.507677
|
OpenGenus/cosmos
| 13,556
| 3,669
| 2,596
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.