File indexing completed on 2024-04-28 04:05:21
0001 /* 0002 SPDX-FileCopyrightText: 2015 Jakob Gruber <jakob.gruber@gmail.com> 0003 0004 SPDX-License-Identifier: GPL-2.0-or-later 0005 */ 0006 0007 #include "boardmap.h" 0008 0009 #include <qglobal.h> 0010 #include <QRandomGenerator> 0011 0012 static int box_count(const QList<Board::State> &data) { 0013 int count = 0; 0014 for (int i = 0; i < data.size(); i++) { 0015 if (data[i] != Board::Nothing) { 0016 count++; 0017 } 0018 } 0019 return count; 0020 } 0021 0022 BoardMap::BoardMap(int width, int height, double box_ratio) : 0023 Board(width, height), m_box_count(width * height * box_ratio) 0024 { 0025 genRandom(); 0026 } 0027 0028 BoardMap::BoardMap(int width, int height, const QList<Board::State> &map) : 0029 Board(width, height), m_box_count(box_count(map)) 0030 { 0031 for (int i = 0; i < map.size(); i++) { 0032 m_state[i] = map[i]; 0033 } 0034 } 0035 0036 void BoardMap::genRandom() { 0037 /* To maintain a uniformly random selection of k elements: 0038 * element i enters the selection with probability k/i. */ 0039 0040 QList<int> indices(m_box_count); 0041 auto *generator = QRandomGenerator::global(); 0042 for (int i = 0; i < m_size; i++) { 0043 if (i < m_box_count) { 0044 indices[i] = i; 0045 continue; 0046 } 0047 0048 if (generator->bounded(i) <= m_box_count) { 0049 indices[generator->bounded(indices.size())] = i; 0050 } 0051 } 0052 0053 for (int i = 0; i < indices.size(); i++) { 0054 m_state[indices[i]] = Box; 0055 } 0056 }