text
stringlengths 8
6.88M
|
|---|
class Solution {
private:
int countSmaller(int m, int n, int target){
int count = 0;
for(int i=1;i<=n;i++){
if(m*i > target){
m--;
i--;
}
else
count += m;
}
return count;
}
public:
int findKthNumber(int m, int n, int k) {
int low = 1, high = m*n;
while(low <= high){
int mid = (low + high) / 2;
int count = countSmaller(m, n, mid);
if(count < k)
low = mid + 1;
else
high = mid - 1;
}
return low;
}
};
|
#pragma once
#include "config/area_ip_ptts.hpp"
#include <string>
namespace pd = proto::data;
namespace pc = proto::config;
namespace nora {
namespace scene {
uint64_t parse_ip_to_int(const string& ip);
const pc::area_ip& fetch_area_ip_ptt(const string& ip);
}
}
|
//
// Created by 史浩 on 2020-01-12.
//
#ifndef NDK_OPENGLES_BASEEGLSURFACE_H
#define NDK_OPENGLES_BASEEGLSURFACE_H
#include "EGLCore.h"
#include <GLES2/gl2.h>
class BaseEGLSurface {
public:
BaseEGLSurface(EGLCore* eglCore);
~BaseEGLSurface();
//创建窗口Surface
void createWindowSurface(ANativeWindow* window);
//创建离屏Surface
void createOffscreenSurface(int width,int height);
//获取宽度
int getWidth();
//获取高度
int getHeight();
//释放EGLSurface
void releaseEglSurface();
//切换当前上下文
void makeCurrent();
//交换缓冲区 显示图像
bool swapBuffers();
//设置显示时间戳
void setPresentationTime(long nsecs);
//获取当前帧缓冲
char* getCurrentFrame();
protected:
EGLCore* mEGLCore;
EGLSurface mEGLSurface;
int mWidth;
int mHeight;
};
#endif //NDK_OPENGLES_BASEEGLSURFACE_H
|
// Add the main
#define CATCH_CONFIG_MAIN
#include "externals/Catch/single_include/catch.hpp"
#undef CATCH_CONFIG_MAIN
|
#include "pch.h"
//
union bgra8_t {
// v is ordered with blue being the least and alpha the most significant octett.
uint32_t v;
struct {
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
} c;
};
struct App : winrt::Windows::UI::Xaml::ApplicationT<App> {
void OnLaunched(const winrt::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs&) {
m_root.HorizontalScrollBarVisibility(winrt::Windows::UI::Xaml::Controls::ScrollBarVisibility::Auto);
m_root.VerticalScrollBarVisibility(winrt::Windows::UI::Xaml::Controls::ScrollBarVisibility::Auto);
m_root.ZoomMode(winrt::Windows::UI::Xaml::Controls::ZoomMode::Enabled);
m_root.MinZoomFactor(0.1f);
m_root.MaxZoomFactor(2.0f);
{
const winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout;
const auto flyout_append = [=](winrt::hstring text) -> winrt::Windows::UI::Xaml::Controls::MenuFlyoutItem {
winrt::Windows::UI::Xaml::Controls::MenuFlyoutItem item;
item.Text(text);
flyout.Items().Append(item);
return item;
};
flyout_append(L"load").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->load_file();
});
flyout_append(L"load overlay").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->load_overlay();
});
flyout_append(L"save as jpg").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->save_jpg();
});
flyout_append(L"histogram").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->do_histogram();
});
flyout_append(L"red").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->do_red();
});
flyout_append(L"green").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->do_green();
});
flyout_append(L"blue").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->do_blue();
});
flyout_append(L"grayscale").Click([this](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
this->do_grayscale();
});
m_root.ContextFlyout(flyout);
}
const auto window = winrt::Windows::UI::Xaml::Window::Current();
window.Content(m_root);
window.Activate();
}
private:
winrt::fire_and_forget load_file() {
const winrt::Windows::Storage::Pickers::FileOpenPicker picker;
picker.SuggestedStartLocation(winrt::Windows::Storage::Pickers::PickerLocationId::PicturesLibrary);
picker.FileTypeFilter().ReplaceAll({
L".bmp",
L".gif",
L".ico",
L".jpeg",
L".jpg",
L".png",
L".tiff",
});
const auto file = co_await picker.PickSingleFileAsync();
if (!file) {
return;
}
const auto bitmap = co_await writeable_bitmap_from_file(file);
refresh_image(bitmap);
m_bitmap = bitmap;
}
winrt::fire_and_forget load_overlay() {
const winrt::Windows::Storage::Pickers::FileOpenPicker picker;
picker.SuggestedStartLocation(winrt::Windows::Storage::Pickers::PickerLocationId::PicturesLibrary);
picker.FileTypeFilter().ReplaceAll({
L".bmp",
L".gif",
L".ico",
L".jpeg",
L".jpg",
L".png",
L".tiff",
});
const auto file = co_await picker.PickSingleFileAsync();
if (!file) {
return;
}
const auto buffer = get_buffer_from_writeable_bitmap(m_bitmap);
const auto overlay = co_await writeable_bitmap_from_file(file);
const auto overlay_buffer = get_buffer_from_writeable_bitmap(overlay);
const auto stride = m_bitmap.PixelWidth();
const auto overlay_stride = overlay.PixelWidth();
const auto width = std::min(stride, overlay_stride);
const auto height = std::min(m_bitmap.PixelHeight(), overlay.PixelHeight());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
// Porter-Duff Source Over Destination rule
// Cr = Cs + Cd*(1-As)
// Ar = As + Ad*(1-As)
const auto d = buffer[y * stride + x];
const auto s = overlay_buffer[y * overlay_stride + x];
bgra8_t r;
r.c.b = uint8_t(std::min(255, (s.c.b * s.c.a + d.c.b * (255 - s.c.a)) / 255));
r.c.g = uint8_t(std::min(255, (s.c.g * s.c.a + d.c.g * (255 - s.c.a)) / 255));
r.c.r = uint8_t(std::min(255, (s.c.r * s.c.a + d.c.r * (255 - s.c.a)) / 255));
r.c.a = uint8_t(std::min(255, (s.c.a * s.c.a + d.c.a * (255 - s.c.a)) / 255));
buffer[y * stride + x] = r;
}
}
m_bitmap.Invalidate();
}
winrt::fire_and_forget save_jpg() {
if (!m_bitmap) {
return;
}
const winrt::Windows::Storage::Pickers::FileSavePicker picker;
picker.SuggestedStartLocation(winrt::Windows::Storage::Pickers::PickerLocationId::PicturesLibrary);
picker.FileTypeChoices().Insert(L"JPEG files", winrt::single_threaded_vector<winrt::hstring>({ L".jpg" }));
const auto file = co_await picker.PickSaveFileAsync();
if (!file) {
return;
}
const auto stream = co_await file.OpenAsync(winrt::Windows::Storage::FileAccessMode::ReadWrite);
const winrt::Windows::UI::Xaml::Controls::Slider quality_slider;
quality_slider.Minimum(0);
quality_slider.Maximum(100);
quality_slider.Value(80);
quality_slider.StepFrequency(1);
const winrt::Windows::UI::Xaml::Controls::ContentDialog quality_dialog;
quality_dialog.Title(winrt::Windows::Foundation::PropertyValue::CreateString(L"JPEG Quality"));
quality_dialog.Content(quality_slider);
quality_dialog.PrimaryButtonText(L"Save");
quality_dialog.SecondaryButtonText(L"Cancel");
const auto quality_dialog_result = co_await quality_dialog.ShowAsync();
if (quality_dialog_result != winrt::Windows::UI::Xaml::Controls::ContentDialogResult::Primary) {
return;
}
const auto quality = quality_slider.Value() / 100.0;
const auto encoder_options = winrt::Windows::Graphics::Imaging::BitmapPropertySet();
encoder_options.Insert(L"ImageQuality", winrt::Windows::Graphics::Imaging::BitmapTypedValue(winrt::Windows::Foundation::PropertyValue::CreateDouble(quality), winrt::Windows::Foundation::PropertyType::Single));
const auto encoder = co_await winrt::Windows::Graphics::Imaging::BitmapEncoder::CreateAsync(winrt::Windows::Graphics::Imaging::BitmapEncoder::JpegEncoderId(), stream, encoder_options);
encoder.SetSoftwareBitmap(software_bitmap_from_writable_bitmap(m_bitmap));
encoder.IsThumbnailGenerated(false);
co_await encoder.FlushAsync();
}
void do_histogram() {
if (!m_bitmap) {
return;
}
const auto buffer = get_buffer_from_writeable_bitmap(m_bitmap);
std::array<uint_fast64_t, 256> histogram{ 0 };
for (auto& p : buffer) {
auto c = (p.c.r + p.c.g + p.c.b) / uint8_t(3);
++histogram[c];
}
const auto max = *std::max_element(histogram.begin(), histogram.end());
for (auto& h : histogram) {
h = 256 - (h * 256) / max;
}
const auto stride = m_bitmap.PixelWidth();
for (int x = 0; x < 256; ++x) {
auto h = histogram[x];
for (uint_fast64_t y = h; y < 256; ++y) {
auto index = stride * y + x;
buffer[index].v = y == h ? 0xff000000 : 0xffffffff;
}
}
m_bitmap.Invalidate();
}
void do_grayscale() {
if (!m_bitmap) {
return;
}
const auto buffer = get_buffer_from_writeable_bitmap(m_bitmap);
for (auto& p : buffer) {
p.c.r = p.c.g = p.c.b = (p.c.r + p.c.g + p.c.b) / uint8_t(3);
}
m_bitmap.Invalidate();
}
void do_red() {
if (!m_bitmap) {
return;
}
const auto buffer = get_buffer_from_writeable_bitmap(m_bitmap);
for (auto& p : buffer) {
p.v &= 0xffff0000;
}
m_bitmap.Invalidate();
}
void do_green() {
if (!m_bitmap) {
return;
}
const auto buffer = get_buffer_from_writeable_bitmap(m_bitmap);
for (auto& p : buffer) {
p.v &= 0xff00ff00;
}
m_bitmap.Invalidate();
}
void do_blue() {
if (!m_bitmap) {
return;
}
const auto buffer = get_buffer_from_writeable_bitmap(m_bitmap);
for (auto& p : buffer) {
p.v &= 0xff0000ff;
}
m_bitmap.Invalidate();
}
void refresh_image(const winrt::Windows::UI::Xaml::Media::ImageSource& source) {
const winrt::Windows::UI::Xaml::Controls::Image image;
image.HorizontalAlignment(winrt::Windows::UI::Xaml::HorizontalAlignment::Center);
image.VerticalAlignment(winrt::Windows::UI::Xaml::VerticalAlignment::Center);
image.Source(source);
const winrt::event_token token = image.Loaded([=](const winrt::Windows::Foundation::IInspectable&, const winrt::Windows::UI::Xaml::RoutedEventArgs&) {
image.Loaded(token);
auto scale_x = m_root.ViewportWidth() / image.ActualWidth();
auto scale_y = m_root.ViewportHeight() / image.ActualHeight();
auto scale = float(std::min(scale_x, scale_y));
if (scale < 1) {
m_root.ChangeView({}, {}, scale);
}
});
m_root.Content(image);
}
static winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::UI::Xaml::Media::Imaging::WriteableBitmap> writeable_bitmap_from_file(const winrt::Windows::Storage::StorageFile& file) {
const auto stream = co_await file.OpenReadAsync();
const auto decoder = co_await winrt::Windows::Graphics::Imaging::BitmapDecoder::CreateAsync(stream);
const auto transform = winrt::Windows::Graphics::Imaging::BitmapTransform();
const auto pixel_data_provider = co_await decoder.GetPixelDataAsync(
winrt::Windows::Graphics::Imaging::BitmapPixelFormat::Bgra8,
winrt::Windows::Graphics::Imaging::BitmapAlphaMode::Straight,
transform,
winrt::Windows::Graphics::Imaging::ExifOrientationMode::RespectExifOrientation,
winrt::Windows::Graphics::Imaging::ColorManagementMode::ColorManageToSRgb
);
auto pixel_data = pixel_data_provider.DetachPixelData();
const winrt::Windows::UI::Xaml::Media::Imaging::WriteableBitmap bitmap(decoder.OrientedPixelWidth(), decoder.OrientedPixelHeight());
span_memcpy(get_buffer_from_writeable_bitmap(bitmap), gsl::span<byte>(pixel_data));
return bitmap;
}
static winrt::Windows::Graphics::Imaging::SoftwareBitmap software_bitmap_from_writable_bitmap(const winrt::Windows::UI::Xaml::Media::Imaging::WriteableBitmap& bitmap) {
return winrt::Windows::Graphics::Imaging::SoftwareBitmap::CreateCopyFromBuffer(bitmap.PixelBuffer(), winrt::Windows::Graphics::Imaging::BitmapPixelFormat::Bgra8, bitmap.PixelWidth(), bitmap.PixelHeight());
}
static gsl::span<bgra8_t> get_buffer_from_writeable_bitmap(const winrt::Windows::UI::Xaml::Media::Imaging::WriteableBitmap& bitmap) {
const auto pixel_buffer = bitmap.PixelBuffer();
const auto buffer = pixel_buffer.as<Windows::Storage::Streams::IBufferByteAccess>();
const auto size = pixel_buffer.Length();
byte* data = nullptr;
winrt::check_hresult(buffer->Buffer(&data));
return { reinterpret_cast<bgra8_t*>(data), size / sizeof(bgra8_t) };
}
template<typename T, typename U>
static void span_memcpy(gsl::span<T> dst, gsl::span<U> src) {
memcpy(dst.data(), src.data(), std::min(dst.size_bytes(), src.size_bytes()));
}
winrt::Windows::UI::Xaml::Controls::ScrollViewer m_root;
winrt::Windows::UI::Xaml::Media::Imaging::WriteableBitmap m_bitmap{ nullptr };
};
int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
winrt::Windows::UI::Xaml::Application::Start([](auto&&) {
winrt::make<App>();
});
}
|
#include "util.hpp"
#include <iostream>
void call() {
std::cout << "called" << std::endl;
}
|
#include <iostream>
#include <vector>
using namespace std;
long long determinant(vector< vector<long long> > m)
{
long long ret = 0;
auto n = m.size();
if(n == 1) {
ret = m[0][0];
} else if(n == 2) {
ret = m[0][0] * m[1][1] - m[1][0] * m[0][1];
} else {
// 0 row expand
long long sign = 1ll;
// for each column
for(unsigned int i = 0u; i < n; i++) {
auto mc = m;
mc.erase(mc.begin());
for(unsigned int c = 0u; c < mc.size(); c++) mc[c].erase(mc[c].begin() + i);
ret += sign * m[0][i] * determinant(mc);
sign *= -1ll;
}
}
return ret;
}
int main()
{
vector<vector<long long>> m = {
{ 1ll, 2ll, 7ll },
{ 3ll, 4ll, 8ll },
{ 5ll, 6ll, 9ll }
};
cout << determinant(m) << endl;
return 0;
}
|
//Phoenix_RK
/*
https://leetcode.com/problems/rank-transform-of-an-array/
Given an array of integers arr, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
Rank is an integer starting from 1.
The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
Rank should be as small as possible.
Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]
*/
class Solution {
public:
vector<int> arrayRankTransform(vector<int>& arr) {
vector<int> dup=arr;
vector<int>res;
sort(dup.begin(),dup.end());
auto end=unique(dup.begin(),dup.end());
//since rank is assigned based on occurance of index ..eliminate duplicates..else rank is skipped by the no of dupliactes
for(auto it=arr.begin();it!=arr.end();it++)
{
int x=lower_bound(dup.begin(),end,*it)-dup.begin();
res.push_back(x+1);
}
return res;
}
};
|
/*********************************************************************
** Author: Chris Matian
** Date: 07/20/2017
** Description: This is the class specification file for Taxicab which is included into Taxicab.cpp and possibly the int main() file.
*********************************************************************/
// Class specification file.
#ifndef TAXI_HPP
#define TAXI_HPP
//Box class declaration
class Taxicab {
private:
// Variable Declarations
int xCoord; // X Coordinate
int yCoord; // Y Coordinate
int totalDistance; // Total Distance Travelled
public:
// Constructor Prototypes
Taxicab();
Taxicab(int, int);
// Function Prototypes
int getXCoord();
int getYCoord();
int getDistanceTraveled();
int moveX(int);
int moveY(int);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/quick/dialogs/SaveSessionDialog.h"
#include "adjunct/desktop_pi/DesktopOpSystemInfo.h"
#include "adjunct/desktop_util/sessions/SessionAutoSaveManager.h"
#include "adjunct/quick/widgets/DesktopFileChooserEdit.h"
#include "adjunct/quick/dialogs/SimpleDialog.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/widgets/OpButton.h"
SaveSessionDialog::SaveSessionDialog()
{
}
void SaveSessionDialog::OnInit()
{
OpFile file;
TRAPD(rc, g_pcfiles->GetFileL(PrefsCollectionFiles::WindowsStorageFile, file));
OpString nameonly;
OpString session_name;
if (file.GetFullPath())
{
nameonly.Set(file.GetName(), MAX_PATH-1);
OpString tmp_storage;
session_name.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_SESSION_FOLDER, tmp_storage));
session_name.Append(nameonly);
}
else //default to a name in the session folder
{
OpString tmp_storage;
session_name.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_SESSION_FOLDER, tmp_storage));
session_name.Append(UNI_L("windows.win"));
}
if (nameonly.Length() > 4)
{
nameonly.Delete(nameonly.Length() - 4);
}
SetWidgetText("Sessionfile_edit", nameonly.CStr());
BOOL fUseAtStartup =
(g_pcui->GetIntegerPref(PrefsCollectionUI::StartupType)==STARTUP_HISTORY || g_pcui->GetIntegerPref(PrefsCollectionUI::StartupType)==STARTUP_WINHOMES);
SetWidgetValue( "Use_session_on_startup", fUseAtStartup);
#ifdef PERMANENT_HOMEPAGE_SUPPORT
BOOL permanent_homepage = (1 == g_pcui->GetIntegerPref(PrefsCollectionUI::PermanentHomepage));
if (permanent_homepage)
{
OpCheckBox* startup_checkbox = (OpCheckBox*)GetWidgetByName("Use_session_on_startup");
if (startup_checkbox)
{
startup_checkbox->SetVisibility(FALSE);
}
}
#endif
}
UINT32 SaveSessionDialog::OnOk()
{
return Dialog::OnOk();
}
BOOL SaveSessionDialog::OnInputAction(OpInputAction* action)
{
if (action->GetAction() == OpInputAction::ACTION_OK)
{
OpString filename;
GetWidgetText("Sessionfile_edit", filename);
if (((DesktopOpSystemInfo*)g_op_system_info)->RemoveIllegalFilenameCharacters(filename, TRUE))
{
//make sure it has win as extension
int length = filename.Length();
if (length < 4 || uni_stricmp(UNI_L(".win"), filename.CStr() + (length - 4)))
{
filename.Append(UNI_L(".win"));
}
OpString tmp_storage;
filename.Insert(0, g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_SESSION_FOLDER, tmp_storage));
OpFile file;
OP_STATUS err = file.Construct(filename.CStr());
if (OpStatus::IsSuccess(err))
{
// check if we overwrite an existing file
BOOL exists;
if (OpStatus::IsSuccess(file.Exists(exists)) && exists)
{
OpString message, title;
g_languageManager->GetString(Str::D_OVERWRITE_SESSION_WARNING, message);
g_languageManager->GetString(Str::D_OVERWRITE_SESSION_LABEL, title);
int result = SimpleDialog::ShowDialog(WINDOW_NAME_WARN_OVERWRITE_SESSION, this, message.CStr(), title.CStr(), Dialog::TYPE_YES_NO, Dialog::IMAGE_WARNING);
if (result != Dialog::DIALOG_RESULT_YES)
{
return FALSE;
}
}
// actually save
BOOL use_at_startup = GetWidgetValue("Use_session_on_startup");
BOOL only_save_avtive_window = GetWidgetValue("Only_save_active_window");
g_session_auto_save_manager->SaveCurrentSession(filename.CStr(), FALSE, TRUE, only_save_avtive_window);
if (use_at_startup)
TRAP(err,g_pcfiles->WriteFilePrefL(PrefsCollectionFiles::WindowsStorageFile, &file));
// we might have to change the startup type if he wants to use it at startup
if (use_at_startup)
{
STARTUPTYPE startupType =
STARTUPTYPE(g_pcui->GetIntegerPref(PrefsCollectionUI::StartupType));
if (startupType!=STARTUP_HISTORY || startupType!=STARTUP_WINHOMES)
startupType = STARTUP_HISTORY;
TRAP(err, g_pcui->WriteIntegerL(PrefsCollectionUI::StartupType, startupType));
}
TRAP(err,g_prefsManager->CommitL());
}
}
}
return Dialog::OnInputAction(action);
}
|
// Created on: 2014-10-20
// Created by: Denis BOGOLEPOV
// Copyright (c) 2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepExtrema_ShapeProximity_HeaderFile
#define _BRepExtrema_ShapeProximity_HeaderFile
#include <NCollection_DataMap.hxx>
#include <Precision.hxx>
#include <TColStd_PackedMapOfInteger.hxx>
#include <BRepExtrema_ProximityValueTool.hxx>
#include <BRepExtrema_TriangleSet.hxx>
#include <BRepExtrema_OverlapTool.hxx>
//! @brief Tool class for shape proximity detection.
//!
//! First approach:
//! For two given shapes and given tolerance (offset from the mesh) the algorithm allows
//! to determine whether or not they are overlapped. The algorithm input consists of any
//! shapes which can be decomposed into individual faces (used as basic shape elements).
//!
//! The algorithm can be run in two modes. If tolerance is set to zero, the algorithm
//! will detect only intersecting faces (containing triangles with common points). If
//! tolerance is set to positive value, the algorithm will also detect faces located
//! on distance less than the given tolerance from each other.
//!
//! Second approach:
//! Compute the proximity value between two shapes (handles only edge/edge or face/face cases)
//! if the tolerance is not defined (Precision::Infinite()).
//! In this case the proximity value is a minimal thickness of a layer containing both shapes.
//!
//! For the both approaches the high performance is achieved through the use of existing
//! triangulation of faces. So, poly triangulation (with the desired deflection) should already
//! be built. Note that solution is approximate (and corresponds to the deflection used for
//! triangulation).
class BRepExtrema_ShapeProximity
{
public:
//! Creates empty proximity tool.
Standard_EXPORT BRepExtrema_ShapeProximity (const Standard_Real theTolerance = Precision::Infinite());
//! Creates proximity tool for the given two shapes.
Standard_EXPORT BRepExtrema_ShapeProximity (const TopoDS_Shape& theShape1,
const TopoDS_Shape& theShape2,
const Standard_Real theTolerance = Precision::Infinite());
public:
//! Returns tolerance value for overlap test (distance between shapes).
Standard_Real Tolerance() const
{
return myTolerance;
}
//! Sets tolerance value for overlap test (distance between shapes).
void SetTolerance (const Standard_Real theTolerance)
{
myTolerance = theTolerance;
}
//! Returns proximity value calculated for the whole input shapes.
Standard_Real Proximity() const
{
return Tolerance();
}
//! Loads 1st shape into proximity tool.
Standard_EXPORT Standard_Boolean LoadShape1 (const TopoDS_Shape& theShape1);
//! Loads 2nd shape into proximity tool.
Standard_EXPORT Standard_Boolean LoadShape2 (const TopoDS_Shape& theShape2);
//! Set number of sample points on the 1st shape used to compute the proximity value.
//! In case of 0, all triangulation nodes will be used.
void SetNbSamples1(const Standard_Integer theNbSamples) { myNbSamples1 = theNbSamples; }
//! Set number of sample points on the 2nd shape used to compute the proximity value.
//! In case of 0, all triangulation nodes will be used.
void SetNbSamples2(const Standard_Integer theNbSamples) { myNbSamples2 = theNbSamples; }
//! Performs search of overlapped faces.
Standard_EXPORT void Perform();
//! True if the search is completed.
Standard_Boolean IsDone() const
{
return myOverlapTool.IsDone() || myProxValTool.IsDone();
}
//! Returns set of IDs of overlapped faces of 1st shape (started from 0).
const BRepExtrema_MapOfIntegerPackedMapOfInteger& OverlapSubShapes1() const
{
return myOverlapTool.OverlapSubShapes1();
}
//! Returns set of IDs of overlapped faces of 2nd shape (started from 0).
const BRepExtrema_MapOfIntegerPackedMapOfInteger& OverlapSubShapes2() const
{
return myOverlapTool.OverlapSubShapes2();
}
//! Returns sub-shape from 1st shape with the given index (started from 0).
const TopoDS_Shape& GetSubShape1 (const Standard_Integer theID) const
{
return myShapeList1.Value (theID);
}
//! Returns sub-shape from 1st shape with the given index (started from 0).
const TopoDS_Shape& GetSubShape2 (const Standard_Integer theID) const
{
return myShapeList2.Value (theID);
}
//! Returns set of all the face triangles of the 1st shape.
const Handle(BRepExtrema_TriangleSet)& ElementSet1() const
{
return myElementSet1;
}
//! Returns set of all the face triangles of the 2nd shape.
const Handle(BRepExtrema_TriangleSet)& ElementSet2() const
{
return myElementSet2;
}
//! Returns the point on the 1st shape, which could be used as a reference point
//! for the value of the proximity.
const gp_Pnt& ProximityPoint1() const
{
return myProxPoint1;
}
//! Returns the point on the 2nd shape, which could be used as a reference point
//! for the value of the proximity.
const gp_Pnt& ProximityPoint2() const
{
return myProxPoint2;
}
//! Returns the status of point on the 1st shape, which could be used as a reference point
//! for the value of the proximity.
const ProxPnt_Status& ProxPntStatus1() const
{
return myProxPntStatus1;
}
//! Returns the status of point on the 2nd shape, which could be used as a reference point
//! for the value of the proximity.
const ProxPnt_Status& ProxPntStatus2() const
{
return myProxPntStatus2;
}
private:
//! Maximum overlapping distance.
Standard_Real myTolerance;
//! Is the 1st shape initialized?
Standard_Boolean myIsInitS1;
//! Is the 2nd shape initialized?
Standard_Boolean myIsInitS2;
//! List of subshapes of the 1st shape.
BRepExtrema_ShapeList myShapeList1;
//! List of subshapes of the 2nd shape.
BRepExtrema_ShapeList myShapeList2;
//! Set of all the face triangles of the 1st shape.
Handle(BRepExtrema_TriangleSet) myElementSet1;
//! Set of all the face triangles of the 2nd shape.
Handle(BRepExtrema_TriangleSet) myElementSet2;
//! Number of sample points on the 1st shape used to compute the proximity value
//! (if zero (default), all triangulation nodes will be used).
Standard_Integer myNbSamples1;
//! Number of sample points on the 2nd shape used to compute the proximity value
//! (if zero (default), all triangulation nodes will be used).
Standard_Integer myNbSamples2;
//! Reference point of the proximity value on the 1st shape.
gp_Pnt myProxPoint1;
//! Reference point of the proximity value on the 2st shape.
gp_Pnt myProxPoint2;
//! Status of reference points of the proximity value.
ProxPnt_Status myProxPntStatus1, myProxPntStatus2;
//! Overlap tool used for intersection/overlap test.
BRepExtrema_OverlapTool myOverlapTool;
//! Shape-shape proximity tool used for computation of
//! the minimal diameter of a tube containing both edges or
//! the minimal thickness of a shell containing both faces.
BRepExtrema_ProximityValueTool myProxValTool;
};
#endif // _BRepExtrema_ShapeProximity_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2004 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef FORMVALUETEXTAREA_H
#define FORMVALUETEXTAREA_H
#include "modules/forms/formvalue.h"
#include "modules/display/vis_dev.h" // VD_TEXT_HIGHLIGHT_TYPE
/**
* Represents an input of type TEXTAREA.
*
* @author Daniel Bratell
*/
class FormValueTextArea : public FormValue
{
public:
FormValueTextArea() :
FormValue(VALUE_TEXTAREA),
m_selection_start(0),
m_selection_end(0),
m_selection_direction(SELECTION_DIRECTION_DEFAULT),
m_selection_highlight_type(VD_TEXT_HIGHLIGHT_TYPE_SELECTION),
m_caret_position(-1),
m_listbox_scroll_pos_x(0),
m_listbox_scroll_pos_y(0) {};
// Use base class documentation
virtual FormValue* Clone(HTML_Element *he);
/**
* "Cast" the FormValue to this class. This asserts in debug
* builds if done badly. This should be inlined and be as
* cheap as a regular cast. If it turns out it's not we
* might have to redo this design.
*
* @param val The FormValue pointer that really is a pointer to
* an object of this class.
*/
static FormValueTextArea* GetAs(FormValue* val)
{
OP_ASSERT(val->GetType() == VALUE_TEXTAREA);
return static_cast<FormValueTextArea*>(val);
}
// Use base class documentation
virtual OP_STATUS ResetToDefault(HTML_Element* he);
// Use base class documentation
virtual OP_STATUS GetValueAsText(HTML_Element* he,
OpString& out_value) const;
static OP_STATUS ConstructFormValueTextArea(HTML_Element* he,
FormValue*& out_value);
// Use base class documentation
virtual OP_STATUS SetValueFromText(HTML_Element* he,
const uni_char* in_value);
virtual OP_STATUS SetValueFromText(HTML_Element* he,
const uni_char* in_value,
BOOL use_undo_stack);
// Use base class documentation
virtual BOOL Externalize(FormObject* form_object_to_seed);
// Use base class documentation
virtual void Unexternalize(FormObject* form_object_to_replace);
/**
* Read value from HTML. Called when the end textarea tag is reached.
*/
OP_STATUS SetInitialValue(HTML_Element* he);
#ifdef INTERNAL_SPELLCHECK_SUPPORT
// Use base class documentation
virtual int CreateSpellSessionId(HTML_Element* he, OpPoint *point = NULL);
#endif // INTERNAL_SPELLCHECK_SUPPORT
// Use base class documentation
virtual BOOL IsUserEditableText(HTML_Element* he);
// Use base class documentation
virtual void GetSelection(HTML_Element* he, INT32& start_ofs, INT32& stop_ofs, SELECTION_DIRECTION& selection) const;
// Use base class documentation
virtual void SetSelection(HTML_Element* he, INT32 start_ofs, INT32 stop_ofs, SELECTION_DIRECTION selection);
// Use base class documentation
virtual void SelectAllText(HTML_Element* he);
// Use base class documentation
virtual void SelectSearchHit(HTML_Element* he, INT32 start_ofs, INT32 stop_ofs, BOOL is_active_hit);
// Use base class documentation
virtual void ClearSelection(HTML_Element* he);
// Use base class documentation
virtual INT32 GetCaretOffset(HTML_Element* he) const;
// Use base class documentation
virtual void SetCaretOffset(HTML_Element* he, INT32 caret_ofs);
/**
* Same as GetValueAsText(), but using LF as line terminator
* rather than CRLF, see its documentation.
*
* The different line ending normalization is needed when
* returning the textarea's value back to scripts.
*/
virtual OP_STATUS GetValueAsTextLF(HTML_Element* he,
OpString& out_value) const;
private:
unsigned char& GetHasOwnValueBool() { return GetReservedChar1(); }
const unsigned char& GetHasOwnValueBool() const { return GetReservedChar1(); }
OP_STATUS GetValueFromHTML(HTML_Element* he, OpString& out_value, BOOL with_crlf = TRUE) const;
/**
* To be used when the value isn't external.
*/
INT32 GetMaxTextOffset(HTML_Element* he) const;
/**
* The form control value if the value isn't in a widget.
*/
OpString m_own_value;
/**
* The selection start if there is no widget to ask.
*/
INT32 m_selection_start;
/**
* The selection end if there is no widget to ask.
*/
INT32 m_selection_end;
/**
* The direction of the selection if there is no widget to ask.
*/
SELECTION_DIRECTION m_selection_direction;
/**
* Selection highlight type.
*/
VD_TEXT_HIGHLIGHT_TYPE m_selection_highlight_type;
/**
* caret pos if there is no widget to ask. -1 means "at the end" and is the initial value.
*/
INT32 m_caret_position;
/**
* Used for form restoring, so that listboxes have the right scroll
* position when walking in history.
*/
int m_listbox_scroll_pos_x;
/**
* Used for form restoring, so that listboxes have the right scroll
* position when walking in history.
*/
int m_listbox_scroll_pos_y;
};
#endif // FORMVALUETEXTAREA_H
|
#ifndef __CAMERA_H__
#define __CAMERA_H__
#include "SDL/include/SDL.h"
#include "Obj_Player.h"
class Camera
{
public:
Camera();
void FollowPlayer(float dt, Obj_Player * player);
public:
SDL_Rect rect = { 0, 0, 0, 0 };//The actual camera coordinates in the world
SDL_Rect screen_section = { 0, 0, 0, 0 };//The section on the screen it covers (ex. player one gets 0, 0, w/2, h/2)
bool assigned = false;
uint number_player = 0u;
private:
float lerp_factor = 0.f;
};
#endif // !__CAMERA_H__
|
/*
* @lc app=leetcode.cn id=452 lang=cpp
*
* [452] 用最少数量的箭引爆气球
*/
// @lc code=start
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
int m = points.size();
if(m==0)return 0;
sort(points.begin(), points.end(), cmp);
int x_end = points[0][1];
int c = 1;
for(int i=0;i<m;i++)
{
if(points[i][0] > x_end)
{
c++;
x_end = points[i][1];
}
}
return c;
}
static bool cmp(const vector<int> &a, const vector<int> b)
{
return a[1] < b[1];
}
};
// @lc code=end
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void out(vector<int> n){
for(auto i:n){
printf("%d ",i);
}
printf("\n");
}
int main(){
//int型の仮想配列を宣言
vector<int> n;
int youso[5] ={2,6,7,1,3};
for (int i = 0; i<5 ;i++){
//仮想配列に要素を詰め込む
n.push_back(youso[i]);
}
//最大値を最小値を*min_element(n.begin(),n.end())で出力
cout << *max_element(n.begin(),n.end()) << " " << *min_element(n.begin(),n.end()) <<endl;
//出力
out(n);
//昇順ソート
sort(n.begin(),n.end());
out(n);
//降順ソート
sort(n.begin(),n.end(),greater<int>());
out(n);
}
|
#include "worker.h"
Worker::Worker(int in_client) {
client = in_client;
//allocated buffer
buflen = 1024;
buf = new char[buflen+1];
cache = "";
}
Worker::~Worker() {}
vector<string>
Worker::split(const char *str, char c = ' ') {
vector<string> result;
do
{
const char *begin = str;
while(*str != c && *str)
str++;
result.push_back(string(begin, str));
} while (0 != *str++);
return result;
}
// vector<string>
// Worker::get_subjects(string name) {
// vector<string> subjects;
// //name exists
// if(mailbox.find(name) != mailbox.end()) {
// // cout << "name is found" << endl;
// subjects = mailbox[name].get_subjects();
// }
// return subjects;
// }
void
Worker::handle_client() {
int result = 0;
string message = "";
do {
memset(buf, 0, buflen);
result = recv(client, buf, buflen, 0);
// cout << "handle client, curr message: " << buf << endl;
if(result > 0) {
cache += buf;
message = read_message();
if(message.empty()) {
continue;
}
handle_message(message);
}
else if(result == 0) {
break;
}
else{
cout << "error recv failed from server" << endl;
perror("recv");
exit(-1);
}
} while(result > 0);
}
string
Worker::parse_message(string message) {
// cout << "parsing message: " << message << endl;
vector<string> fields = split(message.c_str());
if(fields.size() <= 0) {
return "error invalid message\n";
}
if(fields[0] == "reset") {
//clear out data structure where messages are stored
Server::mailbox.clear();
return "OK\n";
}
if(fields[0] == "put") {
if(fields.size() >= 4) {
string name = fields[1];
string subject = fields[2];
int length = stoi(fields[3]);
string data = read_put(length);
if(data.empty()) {
return "error could not read entire message";
}
// store_message(name, subject, data);
Server::mailbox.put(name, subject, data);
return "OK\n";
}
else{
return "error invalid message\n";
}
}
if(fields[0] == "list") {
if(fields.size() >= 2) {
string name = fields[1];
string response = Server::mailbox.list(name);
return response;
}
else{
return "error invalid message\n";
}
}
if(fields[0] == "get") {
if(fields.size() >= 3) {
string name = fields[1];
int index = atoi(fields[2].c_str());
string response = Server::mailbox.get(name, index);
return response;
}
else{
return "error invalid message\n";
}
}
return "error invalid message\n";
}
string
Worker::read_message() {
string message = "";
size_t index = cache.find("\n");
if(index == std::string::npos) {
return "";
}
message = cache.substr(0, index);
cache = cache.substr(index+1);
return message;
}
string
Worker::read_put(int length) {
// cout << "read put, length: " << length << endl;
string data = cache;
while(data.length() < length) {
memset(buf,0,buflen);
int d = recv(client,buf,buflen,0);
if(d < 0) {
cout << "d < 0" << endl;
return "";
}
data += buf;
}
if(data.length() > length) {
cache = data.substr(length);
data = data.substr(0, length);
}
else{
cache = "";
}
return data;
}
// void
// Worker::store_message(string name, string subject, string data) {
// mailbox.put(name, subject, data);
// }
void
Worker::handle_message(string message) {
string response = parse_message(message);
send_response(response);
}
void
Worker::send_response(string response) {
send(client, response.c_str(), response.length(), 0);
}
|
// Created on: 1995-12-19
// Created by: Jean Yves LEBEY
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepBuild_Loop_HeaderFile
#define _TopOpeBRepBuild_Loop_HeaderFile
#include <Standard.hxx>
#include <Standard_Boolean.hxx>
#include <TopoDS_Shape.hxx>
#include <TopOpeBRepBuild_BlockIterator.hxx>
#include <Standard_Transient.hxx>
class TopOpeBRepBuild_Loop;
DEFINE_STANDARD_HANDLE(TopOpeBRepBuild_Loop, Standard_Transient)
//! a Loop is an existing shape (Shell,Wire) or a set
//! of shapes (Faces,Edges) which are connex.
//! a set of connex shape is represented by a BlockIterator
class TopOpeBRepBuild_Loop : public Standard_Transient
{
public:
Standard_EXPORT TopOpeBRepBuild_Loop(const TopoDS_Shape& S);
Standard_EXPORT TopOpeBRepBuild_Loop(const TopOpeBRepBuild_BlockIterator& BI);
Standard_EXPORT virtual Standard_Boolean IsShape() const;
Standard_EXPORT virtual const TopoDS_Shape& Shape() const;
Standard_EXPORT const TopOpeBRepBuild_BlockIterator& BlockIterator() const;
Standard_EXPORT virtual void Dump() const;
DEFINE_STANDARD_RTTIEXT(TopOpeBRepBuild_Loop,Standard_Transient)
protected:
Standard_Boolean myIsShape;
TopoDS_Shape myShape;
TopOpeBRepBuild_BlockIterator myBlockIterator;
private:
};
#endif // _TopOpeBRepBuild_Loop_HeaderFile
|
#include "appconfig.h"
AppConfig::AppConfig()
{
config = new QSettings(":/config.ini", QSettings::IniFormat);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
config->setIniCodec(codec);
}
QStringList AppConfig::get(QString group)
{
qDebug() << "AppConfig::get -" << group;
this->config->beginGroup(group);
QStringList keys = this->config->childKeys();
QStringList values;
foreach (const QString &childKey, keys) {
values.append(this->config->value(childKey).toString());
}
this->config->endGroup();
qDebug() << "AppConfig::get:" << values;
return values;
}
QString AppConfig::get(QString group, QString item)
{
return config->value(QString("%1/%2").arg(group, item)).toString();
}
|
#include "ssVector4.h"
namespace ssMath
{
const Vector4 Vector4::ZERO(0,0,0,0);
}
|
#pragma once
#include <iostream>
#include <map>
#include <string>
#include <variant>
#include <vector>
#include <iterator>
using namespace std;
namespace json {
class Node;
using Dict = map<string, Node>;
using Array = vector<Node>;
class ParsingError : public runtime_error {
public:
using runtime_error::runtime_error;
};
class Node final
: private variant<nullptr_t, Array, Dict, bool, int, double, string> {
public:
using variant::variant;
bool IsInt() const {
return holds_alternative<int>(*this);
}
int AsInt() const {
if (!IsInt()) {
throw logic_error("Not an int"s);
}
return get<int>(*this);
}
bool IsPureDouble() const {
return holds_alternative<double>(*this);
}
bool IsDouble() const {
return IsInt() || IsPureDouble();
}
double AsDouble() const {
using namespace literals;
if (!IsDouble()) {
throw logic_error("Not a double"s);
}
return IsPureDouble() ? get<double>(*this) : AsInt();
}
bool IsBool() const {
return holds_alternative<bool>(*this);
}
bool AsBool() const {
if (!IsBool()) {
throw logic_error("Not a bool"s);
}
return get<bool>(*this);
}
bool IsNull() const {
return holds_alternative<nullptr_t>(*this);
}
bool IsArray() const {
return holds_alternative<Array>(*this);
}
const Array& AsArray() const {
if (!IsArray()) {
throw logic_error("Not an array"s);
}
return get<Array>(*this);
}
bool IsString() const {
return holds_alternative<string>(*this);
}
const string& AsString() const {
if (!IsString()) {
throw logic_error("Not a string"s);
}
return get<string>(*this);
}
bool IsMap() const {
return holds_alternative<Dict>(*this);
}
const Dict& AsMap() const {
if (!IsMap()) {
throw logic_error("Not a map"s);
}
return get<Dict>(*this);
}
bool operator==(const Node& rhs) const {
return GetValue() == rhs.GetValue();
}
const variant& GetValue() const {
return *this;
}
};
inline bool operator!=(const Node& lhs, const Node& rhs) {
return !(lhs == rhs);
}
class Document {
public:
explicit Document(Node root)
: root_(move(root)) {
}
const Node& GetRoot() const {
return root_;
}
private:
Node root_;
};
inline bool operator==(const Document& lhs, const Document& rhs) {
return lhs.GetRoot() == rhs.GetRoot();
}
inline bool operator!=(const Document& lhs, const Document& rhs) {
return !(lhs == rhs);
}
Document Load(istream& input);
void Print(const Document& doc, ostream& output);
} // namespace json
|
/*
* magpie_server.cpp
*
* Created on: 2019年8月27日
* Author: fxh7622
*/
#include <string.h>
#include "protocol.h"
#include "interface.h"
#include "main_thread.h"
#include "express_server.h"
const char* VERSION = "1.1.2";
#if defined(_WIN32)
EXPRESS_SERVER_LIB bool open_server(char *bind_ip, int listen_port, char *log_path, char *harq_path, char *base_path, bool same_name_deleted,
ON_EXPRESS_LOGIN on_login, ON_EXPRESS_PROGRESS on_progress, ON_EXPRESS_FINISH on_finished, ON_EXPRESS_BUFFER on_buffer, ON_EXPRESS_DISCONNECT on_disconnect, ON_EXPRESS_ERROR on_error)
#else
bool open_server(char *bind_ip, int listen_port, char *log_path, char *harq_path, char *base_path, bool same_name_deleted,
ON_EXPRESS_LOGIN on_login, ON_EXPRESS_PROGRESS on_progress, ON_EXPRESS_FINISH on_finished, ON_EXPRESS_BUFFER on_buffer, ON_EXPRESS_DISCONNECT on_disconnect, ON_EXPRESS_ERROR on_error)
#endif
{
std::string tmp_bind_ip(bind_ip);
std::string log(log_path);
std::string libso_path(harq_path);
std::string tmp_base_path(base_path);
file_server_thread::get_instance()->init(tmp_bind_ip, listen_port, log, libso_path, tmp_base_path, same_name_deleted, on_login, on_progress, on_finished, on_buffer, on_disconnect, on_error);
return true;
}
#if defined(_WIN32)
EXPRESS_SERVER_LIB void close_server()
#else
void close_server(void)
#endif
{
}
#if defined(_WIN32)
EXPRESS_SERVER_LIB char* version(void)
#else
char* version(void)
#endif
{
return (char*)VERSION;
}
|
#ifndef LUA_SYSTEM_H
#define LUA_SYSTEM_H
#include "../Internal/SingletonTemplate.h"
#include <lua.hpp>
#include <map>
class LuaSystem : public SingletonTemplate<LuaSystem>
{
public:
LuaSystem();
~LuaSystem();
void Init();
void Exit();
float GetField(lua_State*, const char*);
int GetIntValue(lua_State*, const char*);
float GetFloatValue(lua_State*, const char*);
const char* GetString(lua_State*, const char*);
lua_State* GetLuaState(std::string);
void ReloadLuaState(std::string);
void GameSave();
void LoadGame(int);
std::map<std::string, lua_State*> LuaStateList;
};
#endif
|
#include <iostream>
#include <sstream>
#include <bitset>
#include <vector>
using namespace std;
struct Tile {
//This tile object is flexible enough to represent
// 1. A wooden tile piece on our rack
// 2. A wooden tile piece placed on the board
// 3. A blank spot on the board
char letter; //tile's letter (0 if no letter)
int weight; // letter's score (0 if above is zero)
int bonus; // bonus on that tile (only if representing an empty spot on the board
vector<int> coords; // position of tile on board; -1 if in rack
bool anchor; //the tile is an anchor or not
int orient; //which orientation the anchor is. 0 default; 1 horizontal; 2 vertical; 3 both
bitset<26> xchecks;
// coords is {0}(one index array of -1) if tile
// is not on the board.
Tile(){};
Tile(char l, int W, int b, vector<int> c){
letter= l;
weight = W;
bonus = b;
coords = c;
anchor = false;
orient = 0;
xchecks = xchecks.set();
}
};
// Sam
struct Board {
// the board has a one dimensional array of Tiles
vector<Tile> tiles;
int score; //boards are only scored if we have put a move onto it
Tile& getTile(int col, int row){
//the index of a tile with coordinates of (x,y) in the 2D array is (15*x)+y.
return tiles[15*row + col];
}
vector<Tile> getRow(int row){
/* ARGS: row; integer to represent the row
* RETURNS: an vector of tiles in that row.
*/
vector<Tile> r;
for (int i = 0; i < 15; i++){
r.push_back(tiles.at(15*row + i)); //adds each tile in that row to the vector
}
return r;
}
vector<Tile> getCol(int col){
/* ARGS: col; integer to represent a col.
* RETURNS: a vector of tiles in that col
*/
vector<Tile> c;
for (int i= 0; i < 15; i++){
c.push_back(tiles.at(15*i + col));
}
return c;
}
/*
ostream& operator<<(const Board& board){
/* This may or may not be working
* ARGS: const Board& board; an input board
* RETURNS: ostream; an output stream object for <<'ing into cout.
*
* if I do cout << board;, this should return an output stream object that has the board in it
*
* This is a way of printing the board
ostringstream os;//this throws warnings. I probably did something wrong;
for(int i=0;i<15;i++){
for(int j=0;j<15;j++){
Tile tile = getTile(j,i);
if(tile.letter==0) os << '-';
else os << tile.letter;
}
}
return os;
}
*/
void print(){
//Nazim
bool spaced = true; // FIXME set to false before turning in. True inserts spaces for the sake of legibility
// debugging bools
bool printAnchors = true; // FIXME set to false before turning in
int rank = 0;
Tile temp = this->getTile(0,0);
if (spaced) cout << " 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4";
else cout << " 012345678901234";
cout << endl;
for (int y = 0; y < 15; y++){
rank = y;
if (y>9) rank -= 10;
cout << rank << " ";
for (int x = 0; x < 15; x++){
temp = this->getTile(x, y);
if (temp.letter != 0){cout << temp.letter;}
else if (printAnchors && temp.orient != 0) {cout << '@';}
else if (temp.bonus != 0) {cout << temp.bonus;}
else {cout << '-';}
if (spaced) cout << " ";
}
cout << endl;
}
cout << endl;
}
};
|
#if !defined(AFX_POLLINGPPG_H__D44628CF_9282_11D3_B19B_0000E87780F5__INCLUDED_)
#define AFX_POLLINGPPG_H__D44628CF_9282_11D3_B19B_0000E87780F5__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// PollingPpg.h : Declaration of the CPollingPropPage property page class.
////////////////////////////////////////////////////////////////////////////
// CPollingPropPage : See PollingPpg.cpp.cpp for implementation.
class CPollingPropPage : public COlePropertyPage
{
DECLARE_DYNCREATE(CPollingPropPage)
DECLARE_OLECREATE_EX(CPollingPropPage)
// Constructor
public:
CPollingPropPage();
// Dialog Data
//{{AFX_DATA(CPollingPropPage)
enum { IDD = IDD_PROPPAGE_POLLING };
// NOTE - ClassWizard will add data members here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_DATA
// Implementation
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Message maps
protected:
//{{AFX_MSG(CPollingPropPage)
// NOTE - ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_POLLINGPPG_H__D44628CF_9282_11D3_B19B_0000E87780F5__INCLUDED)
|
//
// Created by new on 2016/11/9.
//
#ifndef HTTPSVR_LIB_IP_H
#define HTTPSVR_LIB_IP_H
#include <string>
#include <vector>
#include <map>
using namespace std;
class Lib_Ip {
public:
static FILE* fp;
static map<string, vector<string> > cached;
static char *index;
static int offset;
static bool init();
static vector<string> find(const char* nip);
};
#endif //HTTPSVR_LIB_IP_H
|
#include "dds_uuid.h"
#include "rotate_state_publisher.h"
CRotateStatePublisher::CRotateStatePublisher()
{
}
CRotateStatePublisher::~CRotateStatePublisher()
{
DDS_String_free(m_pDataInstance->id);
}
bool CRotateStatePublisher::Initialize()
{
CDdsUuid uuid;
uuid.GenerateUuid();
m_pDataInstance->id = DDS_String_dup(uuid.c_str());
return true;
}
void CRotateStatePublisher::SetObjectiveId(const DataTypes::Uuid objectiveId)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->objectiveId = DDS_String_dup(objectiveId);
}
}
void CRotateStatePublisher::SetStatus(const DataTypes::Status status)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->status = status;;
}
}
void CRotateStatePublisher::SetActualRate(radians_per_second_t actualRate)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->actualRate = units::unit_cast<double>(actualRate);
}
}
void CRotateStatePublisher::SetMinRate(radians_per_second_t minRate)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->minRate = units::unit_cast<double>(minRate);
}
}
void CRotateStatePublisher::SetMaxRate(radians_per_second_t maxRate)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->maxRate = units::unit_cast<double>(maxRate);
}
}
void CRotateStatePublisher::SetTargetRate(radians_per_second_t targetRate)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->targetRate = units::unit_cast<double>(targetRate);
}
}
bool CRotateStatePublisher::PublishSample()
{
bool bRetVal = false;
DDS_Time_t currentTime;
GetParticipant()->get_current_time(currentTime);
m_pDataInstance->timestamp.sec = currentTime.sec;
m_pDataInstance->timestamp.nanosec = currentTime.nanosec;
bRetVal = Publish();
return bRetVal;
}
bool CRotateStatePublisher::Create(int32_t domain)
{
return TPublisher::Create(domain,
nec::process::ROTATE_STATE,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
|
#include "transform.h"
#include <iostream>
namespace hdd::gamma
{
FormatType::FormatType() :
type(Undefined), inputs(0), outputs(0)
{}
FormatType::FormatType(Transformation_Type t, uint32_t in, uint32_t out) :
type(t), inputs(in), outputs(out)
{}
Transform::Transform(const RawData& rd) :
raw_data(rd), format(0), inputs(0), outputs(0)
{
if (raw_data.Inputs() == 0)
{
throw std::runtime_error("Unable to perform transformation, invalid data format");
}
FormatType ft;
if (raw_data.Outputs() == 0)
{
for (uint32_t i = 0; i < raw_data.Inputs(); ++i)
{
ft.type = TS;
ft.inputs = 0;
ft.outputs = 0;
format.push_back(ft);
}
}
else
{
for (uint32_t i = 0; i < raw_data.Inputs(); ++i)
{
ft.type = Input;
ft.inputs = 1;
ft.outputs = 0;
format.push_back(ft);
}
for (uint32_t i = 0; i < raw_data.Outputs(); ++i)
{
ft.type = Output;
ft.inputs = 0;
ft.outputs = 1;
format.push_back(ft);
}
}
Set_Data_Format();
for (uint32_t i = 0; i < format.size(); ++i)
{
inputs += format[i].inputs;
outputs += format[i].outputs;
}
if (inputs == 0 || outputs == 0)
{
throw std::runtime_error("Unable to perform transformation, there must be at least one input and one output");
}
}
Transform::Transform(const RawData& rd, const std::vector<FormatType>& ft)
: raw_data(rd), format(ft), inputs(0), outputs(0)
{
if (raw_data.Inputs() == 0 || ft.size() != rd.Series())
{
throw std::runtime_error("Unable to perform transformation, invalid data format");
}
for (uint32_t i = 0; i < format.size(); ++i)
{
inputs += format[i].inputs;
outputs += format[i].outputs;
}
if (inputs == 0 || outputs == 0)
{
throw std::runtime_error("Unable to perform transformation, there must be at least one input and one output");
}
}
void Transform::Set_Data_Format()
{
if (!Summarise_All())
{
for (uint32_t i = 0; i < raw_data.Inputs() + raw_data.Outputs(); ++i)
{
std::cout << std::endl << std::endl << "-------------------------------" << std::endl;
Summarise(i);
format[i] = Choose();
}
}
}
bool Transform::Summarise_All()
{
std::cout << std::endl;
for (uint32_t i = 0; i < format.size(); ++i)
{
Summarise(i);
}
if (raw_data.Inputs() > 0 && raw_data.Outputs() > 0)
{
std::cout << std::endl << "Do you wish to change these settings? (y/n) [n]" << std::endl;
char c = '\0';
while (c != '\n' && c != 'y' && c != 'n') std::cin.get(c);
if (c == '\n' || c == 'n') return true;
}
return false;
}
void Transform::Summarise(uint32_t variable)
{
std::cout << "Series " << (variable + 1) << ": ";
switch (format[variable].type)
{
case Input:
std::cout << "Input" << std::endl;
break;
case Output:
std::cout << "Output" << std::endl;
break;
case TS_Input:
std::cout << "Time Series (Input)" << std::endl;
break;
case TS:
std::cout << "Time Series" << std::endl;
break;
}
std::cout << "First value: " << raw_data[0][variable] << std::endl << std::endl;
}
FormatType Transform::Choose()
{
std::cout << "Select transformation type:" << std::endl;
std::cout << " 1. Input" << std::endl;
std::cout << " 2. Output" << std::endl;
std::cout << " 3. Time Series (Input)" << std::endl;
std::cout << " 4. Time Series" << std::endl;
uint32_t choice = 0;
while (choice < 1 || choice > 4)
{
std::cout << std::endl << "Enter choice [1..4]" << std::endl;
std::cin >> choice;
}
FormatType ft;
switch (choice)
{
case 1:
ft.type = Input;
ft.inputs = 1;
ft.outputs = 0;
break;
case 2:
ft.type = Output;
ft.inputs = 0;
ft.outputs = 1;
break;
case 3:
ft.type = TS_Input;
std::cout << "Enter number of input time steps: " << std::endl;
std::cin >> ft.inputs;
ft.outputs = 0;
break;
case 4:
ft.type = TS;
std::cout << "Enter number of input time steps: " << std::endl;
std::cin >> ft.inputs;
std::cout << "Enter number of output time steps: " << std::endl;
std::cin >> ft.outputs;
break;
}
return ft;
}
uint32_t Transform::Inputs() const
{
return inputs;
}
uint32_t Transform::Outputs() const
{
return outputs;
}
uint32_t Transform::Series() const
{
return raw_data.Series();
}
const FormatType& Transform::operator[](const uint32_t index) const
{
if (index > format.size())
{
throw std::runtime_error("System error, index out of bounds");
}
return format[index];
}
}
|
#include "TestGameSystem.h"
TestEntity::TestEntity(void)
{
}
TestEntity::~TestEntity(void)
{
}
void TestEntity::Init()
{
RegisterComponent(&tf);
//render.renderInfo.matrix = &tf.matrix;
// was model matrix, now coords...
//render.renderInfo.uniforms[0].valueFloat = &(render.renderInfo.matrix->m[0]);
RegisterComponent(&render);
bc = BoxCollider();
RegisterComponent(&bc);
Entity::Init();
TextureInfo textureFile = assMan.GetTexture(L"fart\\test-anim.png");
render.InitSprite(textureFile, 4, 3, 0, 0);
animComp.Setup(L"fart\\test-anim_animations.json");
RegisterComponent(&animComp);
/*
particleSys = new dfParticleSystem();
RegisterComponent(particleSys);
particleSys->layer = 300;
particleSys->sInfo.spawnPoint = vec2(100, 100);
particleSys->sInfo.minVeloc = 3;
particleSys->sInfo.maxVeloc = 6;
particleSys->sInfo.minLifespan = 1;
particleSys->sInfo.maxLifespan = 1;
particleSys->sInfo.minAcc = 0;
particleSys->sInfo.maxAcc = 0;
particleSys->sInfo.startColors.push_back(vec4(1,0,0,1));
particleSys->sInfo.startColors.push_back(vec4(0,0,1,1));
particleSys->sInfo.startColors.push_back(vec4(0,1,0,1));
particleSys->sInfo.beginFadeTime = .9f;
particleSys->sInfo.minStartRotation = -180;
particleSys->sInfo.maxStartRotation = 0;
particleSys->sInfo.minRotationSpd = 0;
particleSys->sInfo.maxRotationSpd = 0;
particleSys->sInfo.minParticleSize = 5;
particleSys->sInfo.maxParticleSize = 15;
particleSys->sInfo.fadeSize = 1;
particleSys->sInfo.textures.push_back(assMan.GetTexture(L"fart\\test-particle.png"));
*/
input.AddMappedAnalogInput(L"walk x", &input.keyboard.arrowLeft, &input.keyboard.arrowRight);
input.AddMappedAnalogInput(L"walk x", &input.keyboard.a, &input.keyboard.d);
input.AddMappedAnalogInput(L"walk y", &input.keyboard.arrowDown, &input.keyboard.arrowUp);
input.AddMappedAnalogInput(L"walk y", &input.keyboard.s, &input.keyboard.w);
}
void TestEntity::Update()
{
Entity::Update();
float x = input.GetMappedAxis(L"walk x");
float y = input.GetMappedAxis(L"walk y");
if(y > 0)
{
RectMove(0, -5.1f, &tf.rectangle);
animComp.Play("walk-up");
}
if(y < 0)
{
RectMove(0, 5, &tf.rectangle);
animComp.Play("walk-down");
}
if(x < 0)
{
RectMove(-5, 0, &tf.rectangle);
animComp.Play("walk-left");
}
if(x > 0)
{
RectMove( 5, 0, &tf.rectangle);
animComp.Play("walk-right");
}
if(input.keyboard.spacebar.tapped)
{
sfxMan.PlaySound(L"fart\\shinyget.wav");
}
//particleSys->sInfo.spawnPoint = tf.rectangle.pos;
//particleSys->sInfo.spawnPoint.x += tf.rectangle.width / 2;
}
// todo
// notes
// 1
// render.renderInfo.matrix = &tf.matrix;
// OK, obviously I want to use the tf matrix as the render matrix.
// any way to make this quicker/easier for a user?
// 2
// having to re-set that matrix uniform to point to the tf matrix is a hassle
// render.renderInfo.uniforms[0].valueFloat = &(render.renderInfo.matrix->m[0]);
// can we automate this somehow?
|
#pragma once
#define _CRT_SECURE_NO_WARNINGS
enum LoggingMessageType {
Debug,
Info,
Error,
Warning
};
#ifndef LOGGER_H
#define LOGGER_H
#include <string>
#include <stdio.h>
#include <cstdarg>
using namespace std;
class cLogger
{
public:
cLogger();
~cLogger();
#ifdef _DEBUG
void Log(LoggingMessageType logType = Info, string file = "unknown", string functionName = "unknown", int line = -1, string format = "", ...);
#else
void Log(LoggingMessageType logType = Info, string format = "", ...);
#endif
};
extern cLogger LoggerInstance;
#ifdef _DEBUG
#define DEBUG_LOG(...) LoggerInstance.Log(Debug, __FILE__, __func__, __LINE__, __VA_ARGS__)
#define INFO_LOG(...) LoggerInstance.Log(Info, __FILE__, __func__, __LINE__, __VA_ARGS__)
#define ERROR_LOG(...) LoggerInstance.Log(Error, __FILE__, __func__, __LINE__, __VA_ARGS__)
#define WARN_LOG(...) LoggerInstance.Log(Warning, __FILE__, __func__, __LINE__, __VA_ARGS__)
#else
#define DEBUG_LOG(...) LoggerInstance.Log(Debug, __VA_ARGS__)
#define INFO_LOG(...) LoggerInstance.Log(Info, __VA_ARGS__)
#define ERROR_LOG(...) LoggerInstance.Log(Error, __VA_ARGS__)
#define WARN_LOG(...) LoggerInstance.Log(Warning, __VA_ARGS__)
#endif
#endif
|
#include <iostream>
using namespace std;
const int maxn = 10005;
int a[maxn], b[maxn];
int main() {
int n, l;
while(~scanf("%d %d", &n, &l)) {
int j = 0, cnt = 0;
for(int i = 0; i < n; i++) {
scanf("%d", a[i]);
}
for(int i = 0; i < n; i++) {
if(a[i] % 2 == 0)
b[j++] = a[i];
}
for(int i = 0; i < j- 1; i++) {
for(int k = i + 1; k < j; k++) {
if(b[i] + b[k] == l) {
cnt++;
}
}
}
}
return 0;
}
|
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(A0, INPUT);
auto ms = micros();
for (int i = 0; i < 1000; ++i)
analogRead(A0);
ms = micros() - ms;
Serial.println(ms);
ms = micros();
for (int i = 0; i < 1000; ++i)
digitalRead(A0);
ms = micros() - ms;
Serial.println(ms);
pinMode(8, OUTPUT);
ms = micros();
for (int i = 0; i < 1000; ++i)
digitalWrite(8, 0);
ms = micros() - ms;
Serial.println(ms);
}
void loop() {
// put your main code here, to run repeatedly:
}
|
#include "BaseDescriptor.h"
BaseDescriptor::BaseDescriptor()
{
}
BaseDescriptor::~BaseDescriptor()
{
}
|
#include "stdafx.h"
#include "FST.h"
#include <iostream>
FST::NODE::NODE()
{
n_relation = 0;
RELATION *relations = NULL;
}
FST::NODE::NODE(short n, RELATION rel, ...)
{
n_relation = n;
RELATION *ptrrel = &rel;
relations = new RELATION[n];
for (short i = 0; i < n; ++i)
relations[i] = ptrrel[i];
}
FST::RELATION::RELATION(char c, short nn)
{
symbol = c;
nnode = nn;
}
FST::FST::FST(char *s, short ns, NODE n, ...)
{
string = s;
nstates = ns;
nodes = new NODE[ns];
NODE *ptrn = &n;
for (int i = 0; i < ns; ++i) nodes[i] = ptrn[i];
rstates = new short[nstates];
memset(rstates, 0xff, sizeof(short)*nstates);
rstates[0] = 0;
position = -1;
}
bool FST::execute(FST & fst)
{
short* rstates = new short[fst.nstates];
memset(rstates, 0xff, sizeof(short)*fst.nstates);
short lstring = strlen(fst.string);
bool rc = true;
for (short i = 0; i < lstring && rc; ++i)
{
fst.position++;
rc = step(fst, rstates);
}
delete[] rstates;
return (rc ? (fst.rstates[fst.nstates - 1] == lstring) : rc);
}
void FST::resolveChain(char * str)
{
std::string string = str;
std::string buff;
int pos = 0;
for (int i = 0; i < string.length(); i++)
{
if (string[i] == '|')
{
buff = string.substr(pos, i - pos);
pos = i + 1;
chain((char*)buff.c_str());
}
}
}
void FST::chain(char *string)
{
FST fst(
string,
9,
NODE(1, RELATION('m', 1)),
NODE(3, RELATION('b', 2), RELATION('b', 1), RELATION('b', 5)),
NODE(3, RELATION('s', 3), RELATION('w', 3), RELATION('h', 3)),
NODE(1, RELATION(';', 4)),
NODE(3, RELATION('b', 5), RELATION('b', 4), RELATION('b', 2)),
NODE(2, RELATION('b', 6), RELATION('b', 5)),
NODE(1, RELATION('r', 7)),
NODE(1, RELATION(';', 8)),
NODE()
);
if (execute(fst))
{
std::cout << "Цепочка " << fst.string << " распознана" << std::endl;
}
else
{
std::cout << "Цепочка " << fst.string << " не распознана" << std::endl;
}
}
bool FST::step(FST& fst, short* &rstates)
{
bool rc = false;
std::swap(rstates, fst.rstates);
for (short i = 0; i < fst.nstates; i++)
{
if (rstates[i] == fst.position)
for (short j = 0; j < fst.nodes[i].n_relation; ++j)
{
if (fst.nodes[i].relations[j].symbol == fst.string[fst.position])
{
fst.rstates[fst.nodes[i].relations[j].nnode] = fst.position + 1;
rc = true;
}
}
}
return rc;
}
|
bool cmp(struct Job a, struct Job b) {
// if(a.dead == b.dead) return a.profit > b.profit;
return a.profit > b.profit;
}
pair<int,int> JobScheduling(Job arr[], int n)
{
// your code here
sort(arr, arr+n, cmp);
for(int i=0; i<n; i++) {
cout << arr[i].id << " " << arr[i].dead << " " << arr[i].profit << endl;
}
int maxProfit = 0;
bool slots[n];
int jCount = 0;
for(int i=0; i<n; i++) {
slots[i] = false;
}
for(int i=0; i<n; i++) {
for(int j=min(n, arr[i].dead) - 1; j>0; i++) {
if(!slots[j]) {
maxProfit += arr[i].profit;
slots[j] = true;
jCount++;
}
}
}
pair <int, int> ans = make_pair(jCount, maxProfit);
return ans;
}
|
#include "cDalek.h"
#include <iostream>
#include "globalStuff.h"
DWORD WINAPI UpdateDalekPosition(void* pInitialData)
{
cDalek* pDalek = (cDalek*)pInitialData;
while (true)
{
pDalek->update(pDalek->dt);
}
return 0;
}
cDalek::cDalek(cGameObject * dalekOb, std::vector<glm::vec3> vecInBlocks, glm::vec3 MF)
{
this->dalekObj = dalekOb;
this->modelForward = MF;
this->dalekForward = getDalekForward(modelForward);
this->vecBlocks = vecInBlocks;
this->dt = 0.f;
this->oldPos = dalekOb->position;
this->moves = 3;
LPDWORD phThread = 0;
DWORD hThread = 0;
HANDLE hThreadHandle = 0;
InitializeCriticalSection(&CR_POSITION);
void* pDalek = (void*)(this);
hThreadHandle = CreateThread(NULL,
0,
&UpdateDalekPosition,
pDalek,
0,
(DWORD*)&phThread);
}
void cDalek::update(float deltaTime)
{
this->dalekForward = getDalekForward(modelForward);
if (moveOrChangeDir(dalekObj, vecBlocks, dalekForward))
{
updatePosition(deltaTime);
}
else
{
float r = ((float)rand() / (RAND_MAX));
std::cout << "random: " << r << std::endl;
if (r > 0.5)
{
dalekObj->adjMeshOrientationEulerAngles(glm::vec3(0.0f, -90.0f, 0.0f), true);
std::cout << "rotating: -90" << std::endl;
}
else
{
dalekObj->adjMeshOrientationEulerAngles(glm::vec3(0.0f, 90.0f, 0.0f), true);
std::cout << "rotating: 90" << std::endl;
}
Sleep(1000);
}
}
bool cDalek::checkCube(glm::vec3 pos, std::vector<glm::vec3> vec_pos)
{
for (int i = 0; i < vec_pos.size(); i++)
{
float dist = glm::distance(pos, vec_pos[i]);
if (dist < 10.0f)
{
return true;
}
}
return false;
}
bool cDalek::moveOrChangeDir(cGameObject* pDalek, std::vector<glm::vec3> vec_blcok_pos, glm::vec3 dalekforward)
{
float cubeSize = 20.0f;
glm::vec3 forwad_1_unit = pDalek->position + dalekforward * cubeSize / 2.0f;
float cubesMove = (float)moves * 20.0f;
glm::vec3 futere_pos = this->oldPos + dalekforward * cubesMove;
if (glm::distance(pDalek->position, futere_pos) > 1.0f) {
if (cDalek::checkCube(forwad_1_unit, vec_blcok_pos))
{
moves = rand() % 5 + 1;
std::cout << "moving: " << moves << " blocks" << std::endl;
this->oldPos = pDalek->position;
return false;
}
else
{
return true;
}
}
else
{
moves = rand() % 5 + 1;
std::cout << "moving: " << moves << " blocks" << std::endl;
this->oldPos = pDalek->position;
return false;
}
}
glm::vec3 cDalek::getDalekForward(glm::vec3 MF)
{
glm::vec3 DalekForward = glm::vec3(0.0f);
glm::vec4 vecForwardDirection_ModelSpace = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
glm::quat charkRotation = this->dalekObj->getQOrientation();
glm::mat4 matCharkRotation = glm::mat4(charkRotation);
DalekForward = matCharkRotation * vecForwardDirection_ModelSpace;
return glm::vec3(DalekForward);
}
void cDalek::updatePosition(float dt)
{
float step = 0.01f * dt;
EnterCriticalSection(&CR_POSITION);
dalekObj->position += dalekForward * step;
LeaveCriticalSection(&CR_POSITION);
}
|
int minimumNumberOfDeletions(string s1) {
int x=s1.size();
int y=s1.size();
string s2 = s1;
reverse(s2.begin(),s2.end());
int dp[x+1][y+1];
for(int i =0;i<x+1;i++) dp[i][0]=0;
for(int i =0;i<y+1;i++) dp[0][i]=0;
for(int i = 1;i<x+1;i++){
for(int j=1;j<y+1;j++){
dp[i][j]=max(dp[i][j-1],dp[i-1][j]);
if(s1[i-1]==s2[j-1]) dp[i][j]=max(1+dp[i-1][j-1],dp[i][j]);
}
}
return s1.length()-dp[x][y];
}
|
#pragma once
#include <map>
#include "bitmap.h"
class CartFile;
class LevelProperties;
class LevelStyle;
class TilePalette;
class TileParts :
public BitmapSurface
{
public:
TileParts();
~TileParts();
bool Load(CartFile& cart, HDC hdc, const LevelProperties& prop,
const LevelStyle& style);
UINT tile_count_;
};
class Tile
{
public:
DWORD part_id;
bool flip_horz,
flip_vert;
};
class TileMap
{
public:
TileMap();
~TileMap();
bool Load(CartFile& cart, const LevelProperties& prop,
const LevelStyle& style);
bool Draw(BitmapSurface& bm, TileParts& parts,
const RECT& clip);
DWORD tilemap_addr_;
WORD tilemap_type_;
WORD map_x_,
map_y_;
WORD map_width_,
map_height_;
WORD map_left_,
map_top_,
map_right_,
map_bottom_;
WORD map_code_;
DWORD map_id_,
map_index_;
typedef std::map<DWORD, Tile> Map;
Map map_;
};
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.app18_TextInputPrice_Value_Property.h>
#include <_root.TextInputPrice.h>
#include <Uno.Bool.h>
#include <Uno.UX.IPropertyListener.h>
#include <Uno.UX.PropertyObject.h>
#include <Uno.UX.Selector.h>
static uType* TYPES[1];
namespace g{
// internal sealed class app18_TextInputPrice_Value_Property :605
// {
static void app18_TextInputPrice_Value_Property_build(uType* type)
{
::TYPES[0] = ::g::TextInputPrice_typeof();
type->SetBase(::g::Uno::UX::Property1_typeof()->MakeType(uObject_typeof(), NULL));
type->SetFields(1,
::TYPES[0/*TextInputPrice*/], offsetof(app18_TextInputPrice_Value_Property, _obj), uFieldFlagsWeak);
}
::g::Uno::UX::Property1_type* app18_TextInputPrice_Value_Property_typeof()
{
static uSStrong< ::g::Uno::UX::Property1_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Uno::UX::Property1_typeof();
options.FieldCount = 2;
options.ObjectSize = sizeof(app18_TextInputPrice_Value_Property);
options.TypeSize = sizeof(::g::Uno::UX::Property1_type);
type = (::g::Uno::UX::Property1_type*)uClassType::New("app18_TextInputPrice_Value_Property", options);
type->fp_build_ = app18_TextInputPrice_Value_Property_build;
type->fp_Get1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, uTRef))app18_TextInputPrice_Value_Property__Get1_fn;
type->fp_get_Object = (void(*)(::g::Uno::UX::Property*, ::g::Uno::UX::PropertyObject**))app18_TextInputPrice_Value_Property__get_Object_fn;
type->fp_Set1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, void*, uObject*))app18_TextInputPrice_Value_Property__Set1_fn;
type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_TextInputPrice_Value_Property__get_SupportsOriginSetter_fn;
return type;
}
// public app18_TextInputPrice_Value_Property(TextInputPrice obj, Uno.UX.Selector name) :608
void app18_TextInputPrice_Value_Property__ctor_3_fn(app18_TextInputPrice_Value_Property* __this, ::g::TextInputPrice* obj, ::g::Uno::UX::Selector* name)
{
__this->ctor_3(obj, *name);
}
// public override sealed object Get(Uno.UX.PropertyObject obj) :610
void app18_TextInputPrice_Value_Property__Get1_fn(app18_TextInputPrice_Value_Property* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval)
{
return *__retval = uPtr(uCast< ::g::TextInputPrice*>(obj, ::TYPES[0/*TextInputPrice*/]))->Value(), void();
}
// public app18_TextInputPrice_Value_Property New(TextInputPrice obj, Uno.UX.Selector name) :608
void app18_TextInputPrice_Value_Property__New1_fn(::g::TextInputPrice* obj, ::g::Uno::UX::Selector* name, app18_TextInputPrice_Value_Property** __retval)
{
*__retval = app18_TextInputPrice_Value_Property::New1(obj, *name);
}
// public override sealed Uno.UX.PropertyObject get_Object() :609
void app18_TextInputPrice_Value_Property__get_Object_fn(app18_TextInputPrice_Value_Property* __this, ::g::Uno::UX::PropertyObject** __retval)
{
return *__retval = __this->_obj, void();
}
// public override sealed void Set(Uno.UX.PropertyObject obj, object v, Uno.UX.IPropertyListener origin) :611
void app18_TextInputPrice_Value_Property__Set1_fn(app18_TextInputPrice_Value_Property* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin)
{
uPtr(uCast< ::g::TextInputPrice*>(obj, ::TYPES[0/*TextInputPrice*/]))->SetValue(v, origin);
}
// public override sealed bool get_SupportsOriginSetter() :612
void app18_TextInputPrice_Value_Property__get_SupportsOriginSetter_fn(app18_TextInputPrice_Value_Property* __this, bool* __retval)
{
return *__retval = true, void();
}
// public app18_TextInputPrice_Value_Property(TextInputPrice obj, Uno.UX.Selector name) [instance] :608
void app18_TextInputPrice_Value_Property::ctor_3(::g::TextInputPrice* obj, ::g::Uno::UX::Selector name)
{
ctor_2(name);
_obj = obj;
}
// public app18_TextInputPrice_Value_Property New(TextInputPrice obj, Uno.UX.Selector name) [static] :608
app18_TextInputPrice_Value_Property* app18_TextInputPrice_Value_Property::New1(::g::TextInputPrice* obj, ::g::Uno::UX::Selector name)
{
app18_TextInputPrice_Value_Property* obj1 = (app18_TextInputPrice_Value_Property*)uNew(app18_TextInputPrice_Value_Property_typeof());
obj1->ctor_3(obj, name);
return obj1;
}
// }
} // ::g
|
/**
* @file ADC_API.cpp
* @brief Contém as funções que retorna o valoro de uma porta ADC
*/
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
/**
* Lê porta analógica de entrada AIN
* @param ain Número da porta em formato de string
* @return Contéudo da porta analógica
*/
int getValueADC(int ain){
ifstream valueFile;
string path = "/sys/bus/iio/devices/iio:device0/in_voltage" + to_string(ain) + "_raw";
valueFile.open(path,ios::in);
if(valueFile.fail()) {
valueFile.close();
}
else {
int readValue;
valueFile >> readValue;
valueFile.close();
return readValue;
}
}
/**
* Lê entrada LDR e retorna-a
* @return Conteúdo na entrada analógica LDR
*/
int getValueLDR(){
return getValueADC(0);
}
/**
* Lê entrada Potenciomêtro e retorna-a
* @return Conteúdo na entrada analógica Potenciomêtro
*/
int getValuePotenciometro(){
return getValueADC(1);
}
|
#include<bits/stdc++.h>
using namespace std;
class CircularQueue{
public:
int rear,front,size,*arr;
CircularQueue(int s){
front = rear= -1;
size = s;
arr = new int[s];
}
void enqueue(int data){
if(front==0&&rear==size-1||(rear==(front-1)%(size-1))){
return;
}
else if(front==-1){
front = rear = 0;
arr[rear] = data;
}
else if(rear==size-1&&front!=0){
rear=0;
arr[rear] = data;
}
else{
rear++;
arr[rear] = data;
}
}
};
int main(){
return 0;
}
|
//**************************************************************************
// File......... : ChannelManager.cpp
// Project...... : VR
// Author....... : Liu Zhi
// Date......... : 2018-10
// Description.. : implementation file for class ChannelManager used as channelID management
//
// History...... : First created by Liu Zhi 2018-10
//
//**************************************************************************
#include "ChannelManager.h"
ChannelManager::ChannelManager()
{
m_size = 0;
}
ChannelManager::~ChannelManager()
{
}
void ChannelManager::Init(int start, int size)
{
m_size = size;
for (int i = start; i < start + m_size; i++)
{
m_ids.push(i);
}
}
int ChannelManager::GetFreeID()
{
std::lock_guard<std::mutex> lock(m_cid_mtx);
if (m_ids.empty())
return -1;
int id = m_ids.front();
m_ids.pop();
return id;
}
void ChannelManager::ReleaseID(int id)
{
std::lock_guard<std::mutex> lock(m_cid_mtx);
m_ids.push(id);
}
int ChannelManager::TotalIDs()
{
return m_size;
}
int ChannelManager::TotalFreeIDs()
{
return (int)m_ids.size();
}
|
#include "powerOfTwo.h"
long int recursTwoToTheN(long int n)
{
long int retVal;
if(n <= 0)
{
return 1;
}
retVal = recursTwoToTheN(n - 1) + recursTwoToTheN(n - 1);
return retVal;
}
void computeTwoToTheN()
{
printf("Enter in a value for n greater than or equal to 0: ");
char *usrIn = (char *) malloc(sizeof(char *));
scanf("%s", usrIn);
long int n = atoi(usrIn);
long int retVal;
if(n >= 30)
{
printf("Thinking...\n");
}
retVal = recursTwoToTheN(n);
printf("2^%ld: %ld\n", n, retVal);
free(usrIn);
}
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <skland/gui/egl-widget.hpp>
#include <skland/gui/mouse-event.hpp>
#include <skland/gui/key-event.hpp>
#include <skland/gui/sub-surface.hpp>
#include <skland/gui/egl-surface.hpp>
#include "internal/abstract-event-handler-redraw-task.hpp"
#include "internal/abstract-view-iterators.hpp"
#include <GLES2/gl2.h>
#include <stdlib.h>
#include <assert.h>
namespace skland {
EGLWidget::EGLWidget()
: EGLWidget(400, 300) {
}
EGLWidget::EGLWidget(int width, int height)
: AbstractWidget(width, height),
sub_surface_(nullptr),
egl_surface_(nullptr),
resize_(false),
animating_(false) {
frame_callback_.done().Set(this, &EGLWidget::OnFrame);
}
EGLWidget::~EGLWidget() {
delete egl_surface_;
delete sub_surface_;
}
void EGLWidget::OnUpdate(AbstractView *view) {
DBG_ASSERT(view == this);
if (nullptr == sub_surface_) {
DBG_ASSERT(nullptr == egl_surface_);
Iterator it(this);
if (nullptr == it.parent()) return;
it = it.parent();
Surface *parent_surface = it.GetSurface();
if (nullptr == parent_surface) return;
sub_surface_ = SubSurface::Create(parent_surface, this);
egl_surface_ = EGLSurface::Get(sub_surface_);
SubSurface::Get(sub_surface_)->SetWindowPosition(x(), y());
egl_surface_->Resize(width(), height());
// surface_->SetDesync();
}
AbstractWidget::OnUpdate(view);
}
Surface *EGLWidget::OnGetSurface(const AbstractView * /* view */) const {
return sub_surface_;
}
void EGLWidget::OnSizeChanged(int width, int height) {
resize_ = true;
// egl_surface_->Resize(this->width(), this->height());
Update();
}
void EGLWidget::OnMouseEnter(MouseEvent *event) {
event->Accept();
}
void EGLWidget::OnMouseLeave(MouseEvent *event) {
event->Accept();
}
void EGLWidget::OnMouseMove(MouseEvent *event) {
event->Accept();
}
void EGLWidget::OnMouseButton(MouseEvent *event) {
event->Accept();
}
void EGLWidget::OnKeyboardKey(KeyEvent *event) {
event->Accept();
}
void EGLWidget::OnDraw(const Context *context) {
if (!animating_) {
if (egl_surface_->MakeCurrent()) {
animating_ = true;
if (resize_) {
resize_ = false;
OnSizeChanged(width(), height());
}
OnInitializeEGL();
egl_surface_->surface()->SetupCallback(frame_callback_);
egl_surface_->SwapBuffers();
egl_surface_->surface()->Commit();
}
}
}
void EGLWidget::OnInitializeEGL() {
glClearColor(0.1, 0.1, .85, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void EGLWidget::OnResizeEGL() {
}
void EGLWidget::OnRenderEGL() {
glClearColor(0.36, 0.85, 0.27, 0.9);
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void EGLWidget::OnFrame(uint32_t /* serial */) {
static int count = 0;
count++;
fprintf(stderr, "on frame: %d\n", count);
if (egl_surface_->MakeCurrent()) {
OnRenderEGL();
egl_surface_->surface()->SetupCallback(frame_callback_);
egl_surface_->SwapBuffers();
egl_surface_->surface()->Commit();
}
}
}
|
// Created on: 2002-12-12
// Created by: data exchange team
// Copyright (c) 2002-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepFEA_NodeGroup_HeaderFile
#define _StepFEA_NodeGroup_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepFEA_HArray1OfNodeRepresentation.hxx>
#include <StepFEA_FeaGroup.hxx>
class TCollection_HAsciiString;
class StepFEA_FeaModel;
class StepFEA_NodeGroup;
DEFINE_STANDARD_HANDLE(StepFEA_NodeGroup, StepFEA_FeaGroup)
//! Representation of STEP entity NodeGroup
class StepFEA_NodeGroup : public StepFEA_FeaGroup
{
public:
//! Empty constructor
Standard_EXPORT StepFEA_NodeGroup();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aGroup_Name, const Handle(TCollection_HAsciiString)& aGroup_Description, const Handle(StepFEA_FeaModel)& aFeaGroup_ModelRef, const Handle(StepFEA_HArray1OfNodeRepresentation)& aNodes);
//! Returns field Nodes
Standard_EXPORT Handle(StepFEA_HArray1OfNodeRepresentation) Nodes() const;
//! Set field Nodes
Standard_EXPORT void SetNodes (const Handle(StepFEA_HArray1OfNodeRepresentation)& Nodes);
DEFINE_STANDARD_RTTIEXT(StepFEA_NodeGroup,StepFEA_FeaGroup)
protected:
private:
Handle(StepFEA_HArray1OfNodeRepresentation) theNodes;
};
#endif // _StepFEA_NodeGroup_HeaderFile
|
#pragma once
#include "PrologInterface.h"
namespace testcommon {
PrologFunctor is_alpha_pred(PrologTerm alpha);
PrologFunctor is_vowel_pred(PrologTerm alpha);
PrologFunctor next_alpha_pred(PrologTerm alpha, PrologTerm next);
void addTestFacts();
int numSolutionsFor(PrologFunctor functor);
}
|
#ifndef TRANF_ENTRADA
#define TRANF_ENTRADA
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int trans_entrada(string valor){
string str = valor;
for(int i=0; i< (int) str.size(); i++)
{ // Converte cada caracter de Str
str[i] = toupper (str[i]); // para maiusculas
}
string entrada[20] = { "ORADEA", "ZERIND", "ARAD", "TIMISOARA", "LUGOJ",
"MEHADIA", "DROBETA","SIBIU", "RVILCEA", "CRAIOVA",
"FAGARAS", "PITESTI", "BUCHAREST", "GIURGIU", "URZICENI",
"VASLUI", "IASI", "NEAMT", "HIRSOVA", "EFORIE"};
for(int i = 0; i < 20; i++){
if(entrada[i] == str)
return i;
}
return 0;
}
#endif // TRANF_ENTRADA
|
/**
* @file np_sin_f4_sw.cc
* @author Gerbrand De Laender
* @date 04/05/2021
* @version 1.0
*
* @brief E091103, Master thesis
*
* @section DESCRIPTION
*
* Single precision (f4) implementation.
*
*/
#include <hls_math.h>
#include "np_sin_f4.h"
void np_sin_f4_sw(float *ina, float *outa, len_t len)
{
for(int i = 0; i < len; i++)
outa[i] = hls::sinf(ina[i]);
}
|
#include "gmock/gmock.h"
#include "simpleProtocolParser.h"
using namespace testing;
class SimpleProtocolParserStub : public SimpleProtocolParser
{
public:
SimpleProtocolParserStub() { trace = ""; }
std::string getTrace() { return trace; }
private:
std::string trace;
void receptionStart() override { trace += "S"; }
void receiveData(char received) override { trace += "D"; }
void appendReceivedData() override { trace += "A"; }
void receptionCompleted() override { trace += "E"; }
};
class SimpleProtocolParserLogicGroup : public Test
{
public:
SimpleProtocolParserStub parser;
};
TEST_F(SimpleProtocolParserLogicGroup, test_start_char_state_change)
{
parser.receiveChar('<');
ASSERT_THAT(parser.getTrace().c_str(), StrEq("S"));
}
TEST_F(SimpleProtocolParserLogicGroup, test_receive_four_char_then_end)
{
parser.receiveChar('<');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar('>');
ASSERT_THAT(parser.getTrace().c_str(), StrEq("SDDDDAE"));
}
TEST_F(SimpleProtocolParserLogicGroup, test_receive_three_data)
{
parser.receiveChar('<');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar(':');
parser.receiveChar('a');
parser.receiveChar('a');
parser.receiveChar(':');
parser.receiveChar('a');
parser.receiveChar('>');
ASSERT_THAT(parser.getTrace().c_str(), StrEq("SDDDDDADDADAE"));
}
|
#include "I2CRemoteControl.h"
I2CRemoteControl::I2CRemoteControl(uint8_t address): address(address) {
// blah blah
}
void I2CRemoteControl::init() {
Wire.begin(address);
}
void I2CRemoteControl::onReceive() {
type = Wire.read();
mode = Wire.read();
pin = Wire.read();
if (mode == 'W') {
pinMode(pin, OUTPUT);
output = Wire.read();
if (type == 'D') {
digitalWrite(pin, output);
}
else {
analogWrite(pin, output);
}
}
}
void I2CRemoteControl::onRequest() {
pinMode(pin, INPUT);
if (type == 'D') {
Wire.write(digitalRead(pin));
}
else {
Wire.write(Phantom::map(analogRead(pin), 0, 1023, 0, 255));
}
}
|
// Copyright (c) 2023 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/config/export_definitions.hpp>
#include <pika/modules/logging.hpp>
#include <cstdlib>
#include <sstream>
#include <string>
namespace pika::detail {
/// from env var name 's' get value if well-formed, otherwise return default
template <typename T>
T get_env_var_as(const char* s, T def) noexcept
{
T val = def;
char* env = std::getenv(s);
if (env)
{
try
{
std::istringstream temp(env);
temp >> val;
}
catch (...)
{
val = def;
LERR_(error) << "get_env_var_as - invalid" << s << val;
}
LDEB_ << "get_env_var_as " << s << val;
}
return val;
}
} // namespace pika::detail
|
//
// Rock.h
// GetFish
//
// Created by zhusu on 15/3/11.
//
//
#ifndef __GetFish__Rock__
#define __GetFish__Rock__
#include "cocos2d.h"
#include "Actor.h"
USING_NS_CC;
class Rock : public Actor
{
public:
static Rock* create(const char* name,int hp);
virtual bool init(const char* name,int hp);
Rock();
virtual ~Rock();
void setNowAnim();
void movementCallback(CCArmature * armature, MovementEventType type, const char * name);
void dis();
void subHp();
void subHp(int hp);
int getHp() const;
private:
int _hp;
int _maxHp;
};
#endif /* defined(__GetFish__Rock__) */
|
#include "MainScene.h"
#include "MyCube.h"
#include "AAInput.h"
MainScene::MainScene() : AAScene()
{
MyCube* cube = new MyCube("body");
this->objects.push_back(cube);
}
MainScene::~MainScene()
{
}
void MainScene::update()
{
for (AAObject* obj : this->objects)
obj->update();
if(AAInput::isKeyDown(GLFW_KEY_UP))
this->camera->moveForward(0.1f);
if (AAInput::isKeyDown(GLFW_KEY_DOWN))
this->camera->moveBackward(0.1f);
if (AAInput::isKeyDown(GLFW_KEY_RIGHT))
this->camera->moveRight(0.1f);
if (AAInput::isKeyDown(GLFW_KEY_LEFT))
this->camera->moveLeft(0.1f);
std::pair<double, double> currentMousePos = AAInput::getMousePos();
double x_delta = previousMousePos.first - currentMousePos.first;
double y_delta = previousMousePos.second - currentMousePos.second;
if (x_delta != 0)
this->camera->rotateLeft(x_delta);
if (y_delta != 0)
this->camera->rotateDown(y_delta);
previousMousePos = currentMousePos;
}
|
/* leetcode 142
*
*
*
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) {
return false;
}
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
ListNode *detectCycle(ListNode *head) {
if (!hasCycle(head)) {
return nullptr;
}
ListNode* ans;
ListNode* fast = head;
ListNode* slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
break;
}
}
fast = head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
};
/************************** run solution **************************/
bool _solution_run(ListNode *head)
{
return false;
}
#define USE_SOLUTION_CUSTOM
string _solution_custom(TestCases &tc)
{
string a = tc.get<string>();
int pos = tc.get<int>();
ListNode *head = StringIntToCycleListNode(a, pos);
Solution leetcode_142;
ListNode *ans = leetcode_142.detectCycle(head);
if (ans == nullptr) {
return "no cycle";
} else {
return "tail connnects to node index " + convert<string>(pos);
}
}
/************************** get testcase **************************/
#ifdef USE_GET_TEST_CASES_IN_CPP
vector<string> _get_test_cases_string()
{
return {};
}
#endif
|
// CalcFactorialNumb.cpp : This file contains the 'main' function. Program execution begins and ends there.
//When using for loops, you should know the number of itereation you will need.
#include <iostream>
using namespace std;
void main()
{
int number;
cout << "Number:";
cin >> number;
int factorial = 1;
if (number <= 0)
cout << "Invalid input.\n";
else {
for (int i = 1; i <= number; i++) {
factorial = factorial * i;
}
cout << "Factorial of " << number << " is... " << factorial;
}
}
|
//
// EPITECH PROJECT, 2018
// nanotekspice
// File description:
// simulate chipsets
//
#include "Components.hpp"
Components::Components()
{
this->init_component_tab();
}
Components::~Components()
{
}
void Components::init_component_tab()
{
this->_my_components.push_back("4001");
this->_my_components.push_back("4011");
this->_my_components.push_back("4030");
this->_my_components.push_back("4069");
this->_my_components.push_back("4071");
this->_my_components.push_back("4081");
}
int Components::find_in_component_tab(std::string str)
{
int i = 0;
int tmp;
while (i < _my_components.size())
{
tmp = str.compare(0, 4, this->_my_components[i]);
if (tmp == 0)
return (i);
i = i + 1;
}
return (-1);
}
std::vector<std::string> Components::getComponentTab()
{
return (this->_my_components);
}
|
// loader.cc
// 1/27/2013
#include "config.h"
#include "loader.h"
#include "driver/maindriver.h"
#include "windbg/inject.h"
#include "windbg/util.h"
#include "hijack/hijackmodule.h"
#include "qtembedplugin/pluginmanager.h"
#include "util/location.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QTextCodec>
#ifdef VNRAGENT_ENABLE_APPRUNNER
#include "qtembedapp/applicationrunner.h"
#endif // VNRAGENT_ENABLE_APPRUNNER
#ifdef VNRAGENT_DEBUG
# include "util/msghandler.h"
#endif // VNRAGENT_DEBUG
#define DEBUG "loader"
#include "sakurakit/skdebug.h"
// Global variables
namespace { // unnamed
QCoreApplication *createApplication_(HINSTANCE hInstance)
{
static char arg0[MAX_PATH * 2]; // in case it is wchar
static char *argv[] = { arg0, nullptr };
static int argc = 1;
::GetModuleFileNameA(hInstance, arg0, sizeof(arg0)/sizeof(*arg0));
return new QCoreApplication(argc, argv);
}
// Persistent data
MainDriver *driver_;
#ifdef VNRAGENT_ENABLE_APPRUNNER
QtEmbedApp::ApplicationRunner *appRunner_;
#endif // VNRAGENT_ENABLE_APPRUNNER
} // unnamed namespace
// Loader
void Loader::initWithInstance(HINSTANCE hInstance)
{
//::GetModuleFileNameW(hInstance, MODULE_PATH, MAX_PATH);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
//QTextCodec::setCodecForCStrings(codec);
//QTextCodec::setCodecForTr(codec);
//::localizePluginManager();
QtEmbedPlugin::PluginManager::globalInstance()->setPrefix(Util::qtPrefix());
::createApplication_(hInstance);
#ifdef VNRAGENT_DEBUG
Util::installDebugMsgHandler();
#endif // VNRAGENT_DEBUG
DOUT(QCoreApplication::applicationFilePath());
::driver_ = new MainDriver;
// Hijack UI threads
{
WinDbg::ThreadsSuspender suspendedThreads; // lock all threads
Hijack::overrideModules();
}
#ifdef VNRAGENT_ENABLE_APPRUNNER
::appRunner_ = new QtEmbedApp::ApplicationRunner(qApp, QT_EVENTLOOP_INTERVAL);
::appRunner_->start();
#else
qApp->exec(); // block here
#endif // VNRAGENT_ENABLE_APPRUNNER
}
void Loader::destroy()
{
if (::driver_) {
::driver_->quit();
#ifdef VNRAGENT_ENABLE_UNLOAD
::driver_->requestDeleteLater();
::driver_ = nullptr;
#endif // VNRAGENT_ENABLE_UNLOAD
}
#ifdef VNRAGENT_ENABLE_APPRUNNER
if (::appRunner_ && ::appRunner_->isActive()) {
::appRunner_->stop(); // this class is not deleted
#ifdef VNRAGENT_ENABLE_UNLOAD
delete ::appRunner_;
::appRunner_ = nullptr;
#endif // VNRAGENT_ENABLE_UNLOAD
}
#endif // VNRAGENT_ENABLE_APPRUNNER
if (qApp) {
qApp->quit();
qApp->processEvents(); // might hang here
#ifdef VNRAGENT_ENABLE_UNLOAD
delete qApp;
#endif // VNRAGENT_ENABLE_UNLOAD
}
}
// EOF
|
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
#include <Rmath.h>
#include <omp.h>
using namespace arma;
using namespace Rcpp;
using namespace std;
// [[Rcpp::plugins(openmp)]]
// [[Rcpp::depends("RcppArmadillo")]]
void update_theta(arma::mat &theta_t, const arma::mat &y_t, const arma::mat &mu_t, const arma::mat &beta_t,
const arma::uvec &clas_cell_t, const arma::vec &sigma_sq_t, const arma::vec &scale_factor_est,
const arma::uvec &S_vec_t, const int &G,
const int &total_cell_num, const double &tau_theta, const int &n_threads) {
int g;
arma::mat theta_star = theta_t + randn(total_cell_num, G)*tau_theta;
arma::mat tmp = randu(total_cell_num, G);
#pragma omp parallel shared(theta_t, theta_star, tmp) private(g) num_threads(n_threads)
{
#pragma omp for schedule(auto)
for (g = 0; g < G; g++) {
arma::vec theta_star_g = theta_star.col(g);
arma::vec theta_g = theta_t.col(g);
arma::vec tmp_g = tmp.col(g);
//calculate the acceptance probability
arma::vec part1 = - (scale_factor_est % (exp(theta_star_g) - exp(theta_g)));
arma::vec part2 = y_t.col(g) % (theta_star_g - theta_g);
arma::vec mu_t_g = mu_t.row(g).t();
arma::vec beta_t_g = beta_t.row(g).t();
arma::vec part3 = -(theta_star_g-theta_g)%(theta_star_g+theta_g-2.0*(mu_t_g(clas_cell_t)+
beta_t_g(S_vec_t)))/(2.0*sigma_sq_t(g));
arma::vec log_r = part1 + part2 + part3;
arma::vec r = exp(log_r);
//update theta_t for gene g
arma::uvec ind = arma::find(tmp_g < r);
theta_g(ind) = theta_star_g(ind);
theta_t.col(g) = theta_g;
}
}
}
arma::mat l_factorial(arma::mat x) {
int x_row = x.n_rows;
int x_col = x.n_cols;
arma::mat fa(x_row, x_col);
for (int i = 0; i < x_row; i++) {
for (int t = 0; t < x_col; t++) {
fa(i,t) = Rcpp::internal::lfactorial(x(i,t));
}
}
return fa;
}
void update_y(arma::mat &y_t, const arma::mat &theta_t, const arma::mat &ind_zero, const arma::vec &scale_factor_est,
const arma::vec &lambda0_t, const arma::vec &lambda1_t, const int &G, const int &total_cell_num,
const int &radius, const int &n_threads) {
int g;
arma::vec rad = arma::regspace(-radius, 1, radius);
arma::mat y_star = y_t;
arma::uvec ind_0 = arma::find(ind_zero == true);
y_star(ind_0) = y_t(ind_0) + Rcpp::RcppArmadillo::sample(rad, ind_0.n_elem, true);
arma::mat tmp_unif = randu(total_cell_num, G);
#pragma omp parallel shared(y_t, y_star, tmp_unif) private(g) num_threads(n_threads)
{
#pragma omp for schedule(auto)
for (g = 0; g < G; g++) {
arma::vec y_g = y_t.col(g);
arma::vec theta_g = theta_t.col(g);
arma::vec y_star_g = y_star.col(g);
arma::uvec ind_0 = arma::find(ind_zero.col(g) == true);
int ind_nzero = ind_0.n_elem;
if (ind_nzero > 0) {
//calculate the acceptance probability for subject j
arma::vec r(total_cell_num, fill::zeros);
arma::vec ind_zero_g = ind_zero.col(g);
arma::uvec ind_tmp = arma::find((y_star_g >= 0) && (ind_zero_g == true) && (y_g >= 0));
arma::uvec ind_0_1 = arma::find((y_star_g >= 0) && (ind_zero_g == true) && (y_g > 0));
arma::uvec ind_1_0 = arma::find((y_star_g > 0) && (ind_zero_g == true) && (y_g >= 0));
if (ind_tmp.n_elem > 0) {
arma::vec part1 = (theta_g(ind_tmp) + log(scale_factor_est(ind_tmp)))%(y_star_g(ind_tmp) - y_g(ind_tmp));
arma::vec part2 = l_factorial(y_g(ind_tmp)) - l_factorial(y_star_g(ind_tmp));
r(ind_tmp) = exp(part1 + part2);
}
if (ind_0_1.n_elem > 0) {
arma::vec part3 = arma::normcdf(lambda0_t(g) + lambda1_t(g) * log2(y_g(ind_0_1)+1.0));
r(ind_0_1) = r(ind_0_1)/part3;
}
if (ind_1_0.n_elem > 0) {
arma::vec part4 = arma::normcdf(lambda0_t(g) + lambda1_t(g) * log2(y_star_g(ind_1_0)+1.0));
r(ind_1_0) = r(ind_1_0)%part4;
}
//update y_t for subject j
arma::vec tmp_unif_g = tmp_unif.col(g);
arma::uvec ind = arma::find(tmp_unif_g < r);
if (ind.n_elem > 0) {
y_g(ind) = y_star_g(ind);
y_t.col(g) = y_g;
}
}
}
}
}
void update_mu(arma::mat &mu_t, const arma::mat &theta_t, const arma::mat &beta_t, const arma::vec &sigma_sq_t,
const arma::uvec &clas_cell_t, const arma::uvec &S_vec_t,
const int &K, const int &G, const double &eta_mu, const double &tau_sq_mu) {
for (int k = 0; k < K; k++) {
arma::vec tmp1(G, fill::zeros);
double tmp2 = 0;
arma::uvec ind_k = arma::find(clas_cell_t == k);
if (ind_k.n_elem > 0) {
arma::uvec S_k = S_vec_t(ind_k);
tmp1 = arma::sum(theta_t.rows(ind_k).t() - beta_t.cols(S_k), 1);
tmp2 = ind_k.n_elem;
}
arma::vec sd = 1.0/(tmp2/sigma_sq_t + 1.0/tau_sq_mu);
arma::vec avg = (tmp1/sigma_sq_t + eta_mu/tau_sq_mu) % sd;
sd = sqrt(sd);
for (int i = 0; i < G; i++){
mu_t(i,k) = R::rnorm(avg(i), sd(i));
}
}
}
void update_beta(arma::mat &beta_t, const arma::mat &theta_t, const arma::mat &mu_t, const arma::vec &sigma_sq_t,
const arma::uvec &clas_cell_t, const arma::uvec &S_vec_t,
const int &L, const int &G, const double &eta_beta, const double &tau_sq_beta) {
for (int ell = 0; ell < L; ell++) {
arma::vec tmp1(G, fill::zeros);
double tmp2 = 0;
arma::uvec ind_ell = arma::find(S_vec_t == ell);
if (ind_ell.n_elem > 0) {
arma::uvec clas_cell_ell = clas_cell_t(ind_ell);
tmp1 = arma::sum(theta_t.rows(ind_ell).t() - mu_t.cols(clas_cell_ell), 1);
tmp2 = ind_ell.n_elem;
}
arma::vec sd = 1.0/(tmp2/sigma_sq_t + 1.0/tau_sq_beta);
arma::vec avg = (tmp1/sigma_sq_t + eta_beta/tau_sq_beta) % sd;
sd = sqrt(sd);
for (int i = 0; i < G; i++){
beta_t(i,ell) = R::rnorm(avg(i), sd(i));
}
}
}
void update_mu_prior(double &eta_mu, double &tau_sq_mu, const arma::mat &mu, const int &K, const int &G) {
double mu_var = tau_sq_mu/(G*K);
double mu_mean = arma::accu(mu)/(G*K);
double eta_mu_star = R::rnorm(mu_mean, sqrt(mu_var));
double shape = (G*K - 1.0)/2.0;
double scale = 2.0/arma::accu(pow(mu-eta_mu,2));
double tau_sq_mu_star = 1.0/arma::randg(distr_param(shape,scale));
eta_mu = eta_mu_star;
tau_sq_mu = tau_sq_mu_star;
}
void update_beta_prior(double &eta_beta, double &tau_sq_beta, arma::mat beta, const int &L, const int &G, const int &S_0) {
double beta_var = tau_sq_beta/(G*(L-1.0));
beta.shed_col(S_0);
double beta_mean = arma::accu(beta)/(G*(L-1.0));
double eta_beta_star = R::rnorm(beta_mean, sqrt(beta_var));
double shape = (G*(L-1.0) - 1.0)/2.0;
double scale = 2.0/arma::accu(pow(beta-eta_beta,2));
double tau_sq_beta_star = 1.0/arma::randg(distr_param(shape,scale));
eta_beta = eta_beta_star;
tau_sq_beta = tau_sq_beta_star;
}
void update_sigma_sq(arma::vec &sigma_sq_t, const arma::mat &theta_t, const arma::mat &mu_t, const arma::mat &beta_t,
const arma::uvec &clas_cell_t, const arma::uvec &S_vec_t, const int &G, const int &total_cell_num, const int &n_threads) {
double shape = total_cell_num/2.0;
arma::vec scale_vec(G, fill::zeros);
int g;
#pragma omp parallel shared(scale_vec) private(g) num_threads(n_threads)
{
#pragma omp for schedule(auto)
for (g = 0; g < G; g++) {
arma::vec theta_g = theta_t.col(g);
arma::vec mu_g = mu_t.row(g).t();
arma::vec beta_g = beta_t.row(g).t();
double tmp = arma::sum(pow(theta_g - mu_g(clas_cell_t) - beta_g(S_vec_t), 2))/2.0;
scale_vec(g) = 1.0/tmp;
}
}
for (g = 0; g < G; g++) {
double rgam = arma::randg(distr_param(shape,scale_vec(g)));
sigma_sq_t(g) = 1.0/rgam;
}
}
double ldnorm(const arma::vec &x, const arma::vec &mu, const arma::vec &sigma){
double y = arma::sum(-(x-mu)%(x-mu)/2.0/sigma/sigma - log(sigma * datum::sqrt2pi));
return y;
}
void update_clas(arma::uvec &S_t, arma::uvec &S_vec_t, arma::uvec &clas_cell_t, const arma::mat &theta_t, const arma::mat &mu_t, const arma::mat &beta_t, const arma::mat &Pi_t,
const arma::uvec &ind_stat_cell, const arma::vec &sigma_sq_t, const arma::vec &phi_t, const arma::vec &n_cell,
const int &G, const int &total_cell_num, const int &L, const int &K, const int &m, const int &n_threads) {
arma::vec sigma_t = sqrt(sigma_sq_t);
int j;
arma::uvec phi_n_zero = arma::find(phi_t > 0);
arma::vec S_range = regspace(0, 1, L-1);
arma::vec Cell_range = regspace(0, 1, K-1);
arma::mat prob_S_mat(L, m);
arma::mat prob_Cell_mat(K, total_cell_num);
#pragma omp parallel shared(S_t, S_vec_t, sigma_t, clas_cell_t, phi_n_zero, S_range, Cell_range, prob_S_mat, prob_Cell_mat) private(j) num_threads(n_threads)
{
#pragma omp for schedule(auto)
for (j = 0; j < m; j++) {
arma::mat theta_j = theta_t.rows((ind_stat_cell(j)-1), (ind_stat_cell(j) + n_cell(j) - 2));
arma::vec tmp(L);
tmp.fill(- datum::inf);
for (unsigned int ell = 0; ell < phi_n_zero.n_elem; ell++) {
double tmp2 = 0;
arma::vec Pi_ell = Pi_t.col(phi_n_zero(ell));
arma::uvec Pi_ell_n_zero = arma::find(Pi_ell > 0);
for (int i = 0; i < n_cell(j); i++) {
arma::vec tmp1(Pi_ell_n_zero.n_elem, fill::zeros);
for (unsigned int k = 0; k < Pi_ell_n_zero.n_elem; k++) {
tmp1(k) = ldnorm(theta_j.row(i).t(), mu_t.col(Pi_ell_n_zero(k))+beta_t.col(phi_n_zero(ell)), sigma_t);
}
double tmp1_max = max(tmp1);
tmp1 = tmp1 - tmp1_max;
tmp2 += log(arma::sum(Pi_ell(Pi_ell_n_zero)%exp(tmp1))) + tmp1_max;
}
tmp(phi_n_zero(ell)) = tmp2;
}
arma::vec tmp_new = tmp - max(tmp);
tmp_new = exp(tmp_new);
arma::vec prob_S = tmp_new % phi_t;
prob_S = prob_S / arma::sum(prob_S);
prob_S_mat.col(j) = prob_S;
}
#pragma omp critical
{
for (j = 0; j < m; j++) {
arma::vec prob_S_j = prob_S_mat.col(j);
S_t(j) = Rcpp::RcppArmadillo::sample(S_range, 1, false, prob_S_j)(0);
}
}
#pragma omp for schedule(auto)
for (j = 0; j < m; j++) {
S_vec_t.subvec((ind_stat_cell(j)-1), (ind_stat_cell(j) + n_cell(j) - 2)).fill(S_t(j));
arma::mat theta_j = theta_t.rows((ind_stat_cell(j)-1), (ind_stat_cell(j) + n_cell(j) - 2));
arma::uvec Pi_S_n_zero = arma::find(Pi_t.col(S_t(j)) > 0);
for (int i = 0; i < n_cell(j); i++) {
arma::vec tmp(K);
tmp.fill(- datum::inf);
for (unsigned int k = 0; k < Pi_S_n_zero.n_elem; k++) {
tmp(Pi_S_n_zero(k)) = ldnorm(theta_j.row(i).t(), mu_t.col(Pi_S_n_zero(k))+beta_t.col(S_t(j)), sigma_t);
}
arma::vec tmp_new = tmp - max(tmp);
tmp_new = exp(tmp_new);
arma::vec prob_clas = tmp_new % Pi_t.col(S_t(j));
prob_clas = prob_clas / arma::sum(prob_clas);
prob_Cell_mat.col(ind_stat_cell(j) + i - 1) = prob_clas;
}
}
#pragma omp critical
{
for (j = 0; j < m; j++) {
for (int i = 0; i < n_cell(j); i++) {
arma::vec prob_cell = prob_Cell_mat.col(ind_stat_cell(j)-1+i);
clas_cell_t(ind_stat_cell(j)-1+i) = Rcpp::RcppArmadillo::sample(Cell_range, 1, false, prob_cell)(0);;
}
}
}
}
}
void update_phi(arma::vec &phi_t, const arma::uvec &S_t, const double &nu_t, const int &L) {
arma::vec tmp(L, fill::none);
for (int ell = 0; ell < L; ell++) {
arma::uvec ind = arma::find(S_t == ell);
tmp(ell) = ind.n_elem;
}
//update phi_t_prime
arma::vec phi_t_prime(L, fill::ones);
for(int ell = 0; ell < L-1; ell++) {
double rbeta_tmp = rbeta(1,1.0+tmp(ell), nu_t+arma::sum(tmp.tail(L-ell-1)))(0);
if (rbeta_tmp == 1){
rbeta_tmp = rbeta_tmp - pow(10,-5);
}
phi_t_prime(ell) = rbeta_tmp;
}
//update phi_t
phi_t(0) = phi_t_prime(0);
for(int ell = 1; ell < L; ell++) {
phi_t(ell) = (1.0-arma::sum(phi_t.head(ell)))*phi_t_prime(ell);
}
}
arma::vec rDirichlet(const arma::vec &alpha_vec) {
arma::vec tmp(alpha_vec.n_elem, fill::zeros);
for (unsigned int i = 0; i < alpha_vec.n_elem; i++) {
tmp(i) = log(arma::randg(distr_param(alpha_vec(i), 1.0)));
}
tmp = tmp - max(tmp);
tmp = exp(tmp);
tmp = tmp/arma::sum(tmp);
return tmp;
}
void update_Pi(arma::mat &Pi_t, const arma::uvec &clas_cell_t, const arma::uvec &S_vec_t, const arma::vec &xi_vec_t,
const double &gam, const int &L, const int &K) {
arma::vec xi_gamma = xi_vec_t * gam;
for (int ell = 0; ell < L; ell++) {
arma::vec tmp0(K, fill::zeros);
arma::uvec ind_ell = arma::find(S_vec_t == ell);
if (ind_ell.n_elem > 0) {
arma::uvec clas_cell_ell = clas_cell_t(ind_ell);
for (int k = 0; k < K; k++) {
arma::uvec ind_j = arma::find(clas_cell_ell == k);
tmp0(k) = ind_j.n_elem;
}
}
Pi_t.col(ell) = rDirichlet(tmp0+xi_gamma);
}
}
void update_xi_alpha(arma::vec &xi, arma::vec &xi_prime, double &alpha, const arma::mat &Pi_t, const double &gam,
const int &K, const int &L, const double &a_xi, const double &b_xi) {
//update xi_prime
arma::vec xi_prime_star_tmp = rbeta(K-1, a_xi, b_xi);
arma::vec xi_prime_star(K, fill::none);
xi_prime_star.head(K-1) = xi_prime_star_tmp;
xi_prime_star(K-1) = 1.0;
//update xi_t
arma::vec xi_star(K, fill::none);
xi_star(0) = xi_prime_star(0);
for(int k = 1; k < K; k++) {
xi_star(k) = (1.0-arma::sum(xi_star.head(k)))*xi_prime_star(k);
}
double part1 = arma::sum((a_xi - 1.0) * (log(xi_prime_star_tmp) - log(xi_prime.head(K-1)))+
(alpha + b_xi - 2.0) * (log(1.0-xi_prime_star_tmp) - log(1.0-xi_prime.head(K-1))));
double part2 = L * arma::sum(arma::lgamma(gam * xi) - arma::lgamma(gam * xi_star));
double part3 = gam * arma::sum((xi_star - xi) % arma::sum(log(Pi_t), 1));
double log_r = part1 + part2 + part3;
double r = arma::randu();
if (r < exp(log_r)) {
xi_prime = xi_prime_star;
xi = xi_star;
}
//update alpha
double scale = -1.0/arma::sum(log(1-xi_prime.head(K-1)));
double shape = K;
alpha = arma::randg(distr_param(shape, scale));
}
void update_lambda(arma::vec &lambda0_t, arma::vec &lambda1_t, const arma::mat &y_t, const arma::mat &ind_zero,
const int &G, const double &lam0_0,
const double &lam1_0, const double &Sigma2_lam0,
const double &Sigma2_lam1, const double &sd_lambda0,
const double &sd_lambda1, const int &n_threads) {
int g;
arma::vec lambda1_star = lambda1_t + sd_lambda1*randn(G);
arma::vec lambda0_star = lambda0_t + sd_lambda0*randn(G);
arma::vec tmp = randu(G);
#pragma omp parallel shared(lambda0_t, lambda1_t, lambda1_star, lambda0_star, tmp) private(g) num_threads(n_threads)
{
#pragma omp for schedule(auto)
for (g = 0; g < G; g++) {
double lambda1_g_star = lambda1_star(g);
if (lambda1_g_star < 0) {
double lambda0_g_star = lambda0_star(g);
arma::vec log2_y_g = log2(y_t.col(g) + 1);
arma::uvec ind_x0_yn0 = arma::find(ind_zero.col(g) == true && y_t.col(g) > 0);
arma::uvec ind_n0 = arma::find(ind_zero.col(g) == false);
arma::vec part1 = arma::normcdf(lambda0_g_star + lambda1_g_star * log2_y_g(ind_x0_yn0)) /
arma::normcdf(lambda0_t(g) + lambda1_t(g) * log2_y_g(ind_x0_yn0));
arma::vec part2 = (1 - arma::normcdf(lambda0_g_star + lambda1_g_star * log2_y_g(ind_n0))) /
(1 - arma::normcdf(lambda0_t(g) + lambda1_t(g) * log2_y_g(ind_n0)));
double part3 = exp(-((lambda0_g_star - lambda0_t(g)) * (lambda0_g_star + lambda0_t(g) - 2.0*lam0_0) / Sigma2_lam0 +
(lambda1_g_star - lambda1_t(g)) * (lambda1_g_star + lambda1_t(g) - 2.0*lam1_0) / Sigma2_lam1)/2.0);
double r = arma::prod(part1) * arma::prod(part2) * part3;
double tmp_g = tmp(g);
if (tmp_g < r) {
lambda0_t(g) = lambda0_g_star;
lambda1_t(g) = lambda1_g_star;
}
}
}
}
}
// [[Rcpp::export]]
List MCMC_full(const int n_iter, const int n_save, arma::mat theta_t, arma::mat y_t, arma::mat ind_zero, arma::mat beta_t, arma::mat mu_t, arma::mat Pi_t,
arma::uvec ind_stat_cell, arma::vec phi_t, arma::vec n_cell, arma::vec sigma_sq_t, arma::uvec clas_cell_t, arma::vec lambda0_t, arma::vec lambda1_t,
arma::uvec S_t, arma::uvec S_vec_t, arma::vec xi_vec_t, arma::vec xi_prime_t, const arma::vec scale_factor_est,
double alpha_t, double nu_t, double gam_t, double eta_mu, double tau_sq_mu, double eta_beta, double tau_sq_beta,
const int G, const int total_cell_num, const int L, const int K, const int m,
double tau_theta, int radius, double lam0_0, double lam1_0, double Sigma2_lam0,
double Sigma2_lam1, double sd_lambda0, double sd_lambda1, double a_xi, double b_xi,
bool iter_save = false, int n_threads = 1, int iter_print = 1000, bool class_print = false) {
S_t = S_t - 1;
S_vec_t = S_vec_t - 1;
clas_cell_t = clas_cell_t - 1;
int save_start = n_iter - n_save;
arma::mat S_save(L, m, fill::zeros);
arma::mat Cell_save(K, total_cell_num, fill::zeros);
arma::mat mu_save(G, K, fill::zeros);
arma::mat beta_save(G, L, fill::zeros);
arma::mat Pi_save(K, L, fill::zeros);
arma::vec sigma_sq_save(G, fill::zeros);
arma::vec lam0_save(G, fill::zeros);
arma::vec lam1_save(G, fill::zeros);
// double eta_mu_save = 0;
// double tau_sq_mu_save = 0;
// double eta_beta_save = 0;
// double tau_sq_beta_save = 0;
double alpha_save = 0;
arma::vec phi_save(L, fill::zeros);
if (iter_save) {
arma::cube mu_iter(G, K, n_save);
arma::cube beta_iter(G, L, n_save);
arma::mat sigma_sq_iter(G, n_save);
arma::mat lam0_iter(G, n_save);
arma::mat lam1_iter(G, n_save);
// arma::vec eta_mu_iter(n_save);
// arma::vec tau_sq_mu_iter(n_save);
// arma::vec eta_beta_iter(n_save);
// arma::vec tau_sq_beta_iter(n_save);
arma::vec alpha_iter(n_save);
arma::mat phi_iter(L, n_save);
// arma::mat xi_iter(K, n_save);
if (class_print) {
Environment base("package:base");
Function table = base["table"];
SEXP S_table = table(Rcpp::_["..."] = S_t);
irowvec S_out = Rcpp::as<arma::irowvec>(S_table);
SEXP Cell_table = table(Rcpp::_["..."] = clas_cell_t);
irowvec Cell_out = Rcpp::as<arma::irowvec>(Cell_table);
cout<<"Iteration "<< 0 <<endl;
cout<<"Subject"<<endl;
cout<<S_out<<endl;
cout<<"Cell"<<endl;
cout<<Cell_out<<endl;
for (int t_iter = 0; t_iter < n_iter; t_iter++) {
update_theta(theta_t, y_t, mu_t, beta_t, clas_cell_t, sigma_sq_t, scale_factor_est, S_vec_t, G, total_cell_num, tau_theta, n_threads);
update_y(y_t, theta_t, ind_zero, scale_factor_est, lambda0_t, lambda1_t, G, total_cell_num, radius, n_threads);
update_lambda(lambda0_t, lambda1_t, y_t, ind_zero, G, lam0_0, lam1_0, Sigma2_lam0, Sigma2_lam1, sd_lambda0, sd_lambda1, n_threads);
update_mu(mu_t, theta_t, beta_t, sigma_sq_t, clas_cell_t, S_vec_t, K, G, eta_mu, tau_sq_mu);
update_beta(beta_t, theta_t, mu_t, sigma_sq_t, clas_cell_t, S_vec_t, L, G, eta_beta, tau_sq_beta);
mu_t.each_col() += beta_t.col(S_t(0));
beta_t.each_col() -= beta_t.col(S_t(0));
update_mu_prior(eta_mu, tau_sq_mu, mu_t, K, G);
update_beta_prior(eta_beta, tau_sq_beta, beta_t, L, G, S_t(0));
update_sigma_sq(sigma_sq_t, theta_t, mu_t, beta_t, clas_cell_t, S_vec_t, G, total_cell_num, n_threads);
update_clas(S_t, S_vec_t, clas_cell_t, theta_t, mu_t, beta_t, Pi_t, ind_stat_cell, sigma_sq_t, phi_t, n_cell, G, total_cell_num, L, K, m, n_threads);
update_phi(phi_t, S_t, nu_t, L);
update_Pi(Pi_t, clas_cell_t, S_vec_t, xi_vec_t, gam_t, L, K);
update_xi_alpha(xi_vec_t, xi_prime_t, alpha_t, Pi_t, gam_t, K, L, a_xi, b_xi);
SEXP S_table = table(Rcpp::_["..."] = S_t);
irowvec S_out = Rcpp::as<arma::irowvec>(S_table);
SEXP Cell_table = table(Rcpp::_["..."] = clas_cell_t);
irowvec Cell_out = Rcpp::as<arma::irowvec>(Cell_table);
cout<<"Iteration "<< t_iter+1 <<endl;
cout<<"Subject"<<endl;
cout<<S_out<<endl;
cout<<"Cell"<<endl;
cout<<Cell_out<<endl;
if (t_iter >= save_start) {
int save_i = t_iter - save_start;
for (int S_i = 0; S_i < m; S_i++) {
S_save(S_t(S_i),S_i) += 1;
}
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_save(clas_cell_t(C_i),C_i) += 1;
}
mu_save += mu_t;
beta_save += beta_t;
Pi_save += Pi_t;
sigma_sq_save += sigma_sq_t;
lam0_save += lambda0_t;
lam1_save += lambda1_t;
// eta_mu_save += eta_mu;
// tau_sq_mu_save += tau_sq_mu;
// eta_beta_save += eta_beta;
// tau_sq_beta_save += tau_sq_beta;
alpha_save += alpha_t;
phi_save += phi_t;
mu_iter.slice(save_i) = mu_t;
beta_iter.slice(save_i) = beta_t;
sigma_sq_iter.col(save_i) = sigma_sq_t;
lam0_iter.col(save_i) = lambda0_t;
lam1_iter.col(save_i) = lambda1_t;
// eta_mu_iter(save_i) = eta_mu;
// tau_sq_mu_iter(save_i) = tau_sq_mu;
// eta_beta_iter(save_i) = eta_beta;
// tau_sq_beta_iter(save_i) = tau_sq_beta;
alpha_iter(save_i) = alpha_t;
phi_iter.col(save_i) = phi_t;
// xi_iter.col(save_i) = xi_vec_t;
}
}
mu_save /= n_save;
beta_save /= n_save;
Pi_save /= n_save;
sigma_sq_save /= n_save;
lam0_save /= n_save;
lam1_save /= n_save;
// eta_mu_save /= n_save;
// tau_sq_mu_save /= n_save;
// eta_beta_save /= n_save;
// tau_sq_beta_save /= n_save;
alpha_save /= n_save;
phi_save /= n_save;
arma::vec S_est(m);
for (int S_i = 0; S_i < m; S_i++) {
S_est(S_i) = S_save.col(S_i).index_max() + 1;
}
arma::vec Cell_est(total_cell_num);
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_est(C_i) = Cell_save.col(C_i).index_max() + 1;
}
return List::create(Named("subject_subgroup_label")=S_est, Named("cell_type_label")=Cell_est, Named("cell_type_effects")=mu_save, Named("subject_subgroup_effects")=beta_save, Named("cell_type_prop")=Pi_save,
Named("cell_type_effects_post")=mu_iter, Named("subject_subgroup_effects_post")=beta_iter, Named("sigma_sq_post")=sigma_sq_iter, Named("lam0_post")=lam0_iter,
Named("lam1_post")=lam1_iter, Named("alpha_post")=alpha_iter, Named("subject_subgroup_prop_post")=phi_iter,
// Named("eta_mu_iter")=eta_mu_iter, Named("tau_sq_mu_iter")=tau_sq_mu_iter, Named("eta_beta_iter")=eta_beta_iter, Named("tau_sq_beta_iter")=tau_sq_beta_iter,
Named("sigma_sq")=sigma_sq_save, Named("lam0")=lam0_save, Named("lam1")=lam1_save,
// Named("eta_mu")=eta_mu_save, Named("tau_sq_mu")=tau_sq_mu_save, Named("eta_beta")=eta_beta_save, Named("tau_sq_beta")=tau_sq_beta_save,
Named("alpha")=alpha_save, Named("subject_subgroup_prop")=phi_save);
} else {
for (int t_iter = 0; t_iter < n_iter; t_iter++) {
update_theta(theta_t, y_t, mu_t, beta_t, clas_cell_t, sigma_sq_t, scale_factor_est, S_vec_t, G, total_cell_num, tau_theta, n_threads);
update_y(y_t, theta_t, ind_zero, scale_factor_est, lambda0_t, lambda1_t, G, total_cell_num, radius, n_threads);
update_lambda(lambda0_t, lambda1_t, y_t, ind_zero, G, lam0_0, lam1_0, Sigma2_lam0, Sigma2_lam1, sd_lambda0, sd_lambda1, n_threads);
update_mu(mu_t, theta_t, beta_t, sigma_sq_t, clas_cell_t, S_vec_t, K, G, eta_mu, tau_sq_mu);
update_beta(beta_t, theta_t, mu_t, sigma_sq_t, clas_cell_t, S_vec_t, L, G, eta_beta, tau_sq_beta);
mu_t.each_col() += beta_t.col(S_t(0));
beta_t.each_col() -= beta_t.col(S_t(0));
update_mu_prior(eta_mu, tau_sq_mu, mu_t, K, G);
update_beta_prior(eta_beta, tau_sq_beta, beta_t, L, G, S_t(0));
update_sigma_sq(sigma_sq_t, theta_t, mu_t, beta_t, clas_cell_t, S_vec_t, G, total_cell_num, n_threads);
update_clas(S_t, S_vec_t, clas_cell_t, theta_t, mu_t, beta_t, Pi_t, ind_stat_cell, sigma_sq_t, phi_t, n_cell, G, total_cell_num, L, K, m, n_threads);
update_phi(phi_t, S_t, nu_t, L);
update_Pi(Pi_t, clas_cell_t, S_vec_t, xi_vec_t, gam_t, L, K);
update_xi_alpha(xi_vec_t, xi_prime_t, alpha_t, Pi_t, gam_t, K, L, a_xi, b_xi);
if ((t_iter+1) % iter_print == 0) {
// iter_out("step.txt", t_iter);
cout<<"Iteration "<< t_iter+1 <<endl;
}
if (t_iter >= save_start) {
int save_i = t_iter - save_start;
for (int S_i = 0; S_i < m; S_i++) {
S_save(S_t(S_i),S_i) += 1;
}
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_save(clas_cell_t(C_i),C_i) += 1;
}
mu_save += mu_t;
beta_save += beta_t;
Pi_save += Pi_t;
sigma_sq_save += sigma_sq_t;
lam0_save += lambda0_t;
lam1_save += lambda1_t;
// eta_mu_save += eta_mu;
// tau_sq_mu_save += tau_sq_mu;
// eta_beta_save += eta_beta;
// tau_sq_beta_save += tau_sq_beta;
alpha_save += alpha_t;
phi_save += phi_t;
mu_iter.slice(save_i) = mu_t;
beta_iter.slice(save_i) = beta_t;
sigma_sq_iter.col(save_i) = sigma_sq_t;
lam0_iter.col(save_i) = lambda0_t;
lam1_iter.col(save_i) = lambda1_t;
// eta_mu_iter(save_i) = eta_mu;
// tau_sq_mu_iter(save_i) = tau_sq_mu;
// eta_beta_iter(save_i) = eta_beta;
// tau_sq_beta_iter(save_i) = tau_sq_beta;
alpha_iter(save_i) = alpha_t;
phi_iter.col(save_i) = phi_t;
// xi_iter.col(save_i) = xi_vec_t;
}
}
mu_save /= n_save;
beta_save /= n_save;
Pi_save /= n_save;
sigma_sq_save /= n_save;
lam0_save /= n_save;
lam1_save /= n_save;
// eta_mu_save /= n_save;
// tau_sq_mu_save /= n_save;
// eta_beta_save /= n_save;
// tau_sq_beta_save /= n_save;
alpha_save /= n_save;
phi_save /= n_save;
arma::vec S_est(m);
for (int S_i = 0; S_i < m; S_i++) {
S_est(S_i) = S_save.col(S_i).index_max() + 1;
}
arma::vec Cell_est(total_cell_num);
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_est(C_i) = Cell_save.col(C_i).index_max() + 1;
}
return List::create(Named("subject_subgroup_label")=S_est, Named("cell_type_label")=Cell_est, Named("cell_type_effects")=mu_save, Named("subject_subgroup_effects")=beta_save, Named("cell_type_prop")=Pi_save,
Named("cell_type_effects_post")=mu_iter, Named("subject_subgroup_effects_post")=beta_iter, Named("sigma_sq_post")=sigma_sq_iter, Named("lam0_post")=lam0_iter,
Named("lam1_post")=lam1_iter, Named("alpha_post")=alpha_iter, Named("subject_subgroup_prop_post")=phi_iter,
// Named("eta_mu_iter")=eta_mu_iter, Named("tau_sq_mu_iter")=tau_sq_mu_iter, Named("eta_beta_iter")=eta_beta_iter, Named("tau_sq_beta_iter")=tau_sq_beta_iter,
Named("sigma_sq")=sigma_sq_save, Named("lam0")=lam0_save, Named("lam1")=lam1_save,
// Named("eta_mu")=eta_mu_save, Named("tau_sq_mu")=tau_sq_mu_save, Named("eta_beta")=eta_beta_save, Named("tau_sq_beta")=tau_sq_beta_save,
Named("alpha")=alpha_save, Named("subject_subgroup_prop")=phi_save);
}
} else {
if (class_print) {
Environment base("package:base");
Function table = base["table"];
SEXP S_table = table(Rcpp::_["..."] = S_t);
irowvec S_out = Rcpp::as<arma::irowvec>(S_table);
SEXP Cell_table = table(Rcpp::_["..."] = clas_cell_t);
irowvec Cell_out = Rcpp::as<arma::irowvec>(Cell_table);
cout<<"Iteration "<< 0 <<endl;
cout<<"Subject"<<endl;
cout<<S_out<<endl;
cout<<"Cell"<<endl;
cout<<Cell_out<<endl;
for (int t_iter = 0; t_iter < n_iter; t_iter++) {
update_theta(theta_t, y_t, mu_t, beta_t, clas_cell_t, sigma_sq_t, scale_factor_est, S_vec_t, G, total_cell_num, tau_theta, n_threads);
update_y(y_t, theta_t, ind_zero, scale_factor_est, lambda0_t, lambda1_t, G, total_cell_num, radius, n_threads);
update_lambda(lambda0_t, lambda1_t, y_t, ind_zero, G, lam0_0, lam1_0, Sigma2_lam0, Sigma2_lam1, sd_lambda0, sd_lambda1, n_threads);
update_mu(mu_t, theta_t, beta_t, sigma_sq_t, clas_cell_t, S_vec_t, K, G, eta_mu, tau_sq_mu);
update_beta(beta_t, theta_t, mu_t, sigma_sq_t, clas_cell_t, S_vec_t, L, G, eta_beta, tau_sq_beta);
mu_t.each_col() += beta_t.col(S_t(0));
beta_t.each_col() -= beta_t.col(S_t(0));
update_mu_prior(eta_mu, tau_sq_mu, mu_t, K, G);
update_beta_prior(eta_beta, tau_sq_beta, beta_t, L, G, S_t(0));
update_sigma_sq(sigma_sq_t, theta_t, mu_t, beta_t, clas_cell_t, S_vec_t, G, total_cell_num, n_threads);
update_clas(S_t, S_vec_t, clas_cell_t, theta_t, mu_t, beta_t, Pi_t, ind_stat_cell, sigma_sq_t, phi_t, n_cell, G, total_cell_num, L, K, m, n_threads);
update_phi(phi_t, S_t, nu_t, L);
update_Pi(Pi_t, clas_cell_t, S_vec_t, xi_vec_t, gam_t, L, K);
update_xi_alpha(xi_vec_t, xi_prime_t, alpha_t, Pi_t, gam_t, K, L, a_xi, b_xi);
SEXP S_table = table(Rcpp::_["..."] = S_t);
irowvec S_out = Rcpp::as<arma::irowvec>(S_table);
SEXP Cell_table = table(Rcpp::_["..."] = clas_cell_t);
irowvec Cell_out = Rcpp::as<arma::irowvec>(Cell_table);
cout<<"Iteration "<< t_iter+1 <<endl;
cout<<"Subject"<<endl;
cout<<S_out<<endl;
cout<<"Cell"<<endl;
cout<<Cell_out<<endl;
if (t_iter >= save_start) {
for (int S_i = 0; S_i < m; S_i++) {
S_save(S_t(S_i),S_i) += 1;
}
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_save(clas_cell_t(C_i),C_i) += 1;
}
mu_save += mu_t;
beta_save += beta_t;
Pi_save += Pi_t;
sigma_sq_save += sigma_sq_t;
lam0_save += lambda0_t;
lam1_save += lambda1_t;
// eta_mu_save += eta_mu;
// tau_sq_mu_save += tau_sq_mu;
// eta_beta_save += eta_beta;
// tau_sq_beta_save += tau_sq_beta;
alpha_save += alpha_t;
phi_save += phi_t;
}
}
mu_save /= n_save;
beta_save /= n_save;
Pi_save /= n_save;
sigma_sq_save /= n_save;
lam0_save /= n_save;
lam1_save /= n_save;
// eta_mu_save /= n_save;
// tau_sq_mu_save /= n_save;
// eta_beta_save /= n_save;
// tau_sq_beta_save /= n_save;
alpha_save /= n_save;
phi_save /= n_save;
arma::vec S_est(m);
for (int S_i = 0; S_i < m; S_i++) {
S_est(S_i) = S_save.col(S_i).index_max() + 1;
}
arma::vec Cell_est(total_cell_num);
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_est(C_i) = Cell_save.col(C_i).index_max() + 1;
}
return List::create(Named("subject_subgroup_label")=S_est, Named("cell_type_label")=Cell_est, Named("cell_type_effects")=mu_save, Named("subject_subgroup_effects")=beta_save, Named("cell_type_prop")=Pi_save,
Named("sigma_sq")=sigma_sq_save, Named("lam0")=lam0_save, Named("lam1")=lam1_save,
// Named("eta_mu")=eta_mu_save, Named("tau_sq_mu")=tau_sq_mu_save, Named("eta_beta")=eta_beta_save, Named("tau_sq_beta")=tau_sq_beta_save,
Named("alpha")=alpha_save, Named("subject_subgroup_prop")=phi_save);
} else {
for (int t_iter = 0; t_iter < n_iter; t_iter++) {
update_theta(theta_t, y_t, mu_t, beta_t, clas_cell_t, sigma_sq_t, scale_factor_est, S_vec_t, G, total_cell_num, tau_theta, n_threads);
update_y(y_t, theta_t, ind_zero, scale_factor_est, lambda0_t, lambda1_t, G, total_cell_num, radius, n_threads);
update_lambda(lambda0_t, lambda1_t, y_t, ind_zero, G, lam0_0, lam1_0, Sigma2_lam0, Sigma2_lam1, sd_lambda0, sd_lambda1, n_threads);
update_mu(mu_t, theta_t, beta_t, sigma_sq_t, clas_cell_t, S_vec_t, K, G, eta_mu, tau_sq_mu);
update_beta(beta_t, theta_t, mu_t, sigma_sq_t, clas_cell_t, S_vec_t, L, G, eta_beta, tau_sq_beta);
mu_t.each_col() += beta_t.col(S_t(0));
beta_t.each_col() -= beta_t.col(S_t(0));
update_mu_prior(eta_mu, tau_sq_mu, mu_t, K, G);
update_beta_prior(eta_beta, tau_sq_beta, beta_t, L, G, S_t(0));
update_sigma_sq(sigma_sq_t, theta_t, mu_t, beta_t, clas_cell_t, S_vec_t, G, total_cell_num, n_threads);
update_clas(S_t, S_vec_t, clas_cell_t, theta_t, mu_t, beta_t, Pi_t, ind_stat_cell, sigma_sq_t, phi_t, n_cell, G, total_cell_num, L, K, m, n_threads);
update_phi(phi_t, S_t, nu_t, L);
update_Pi(Pi_t, clas_cell_t, S_vec_t, xi_vec_t, gam_t, L, K);
update_xi_alpha(xi_vec_t, xi_prime_t, alpha_t, Pi_t, gam_t, K, L, a_xi, b_xi);
if ((t_iter+1) % iter_print == 0) {
// iter_out("step.txt", t_iter);
cout<<"Iteration "<< t_iter+1 <<endl;
}
if (t_iter >= save_start) {
for (int S_i = 0; S_i < m; S_i++) {
S_save(S_t(S_i),S_i) += 1;
}
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_save(clas_cell_t(C_i),C_i) += 1;
}
mu_save += mu_t;
beta_save += beta_t;
Pi_save += Pi_t;
sigma_sq_save += sigma_sq_t;
lam0_save += lambda0_t;
lam1_save += lambda1_t;
// eta_mu_save += eta_mu;
// tau_sq_mu_save += tau_sq_mu;
// eta_beta_save += eta_beta;
// tau_sq_beta_save += tau_sq_beta;
alpha_save += alpha_t;
phi_save += phi_t;
}
}
mu_save /= n_save;
beta_save /= n_save;
Pi_save /= n_save;
sigma_sq_save /= n_save;
lam0_save /= n_save;
lam1_save /= n_save;
// eta_mu_save /= n_save;
// tau_sq_mu_save /= n_save;
// eta_beta_save /= n_save;
// tau_sq_beta_save /= n_save;
alpha_save /= n_save;
phi_save /= n_save;
arma::vec S_est(m);
for (int S_i = 0; S_i < m; S_i++) {
S_est(S_i) = S_save.col(S_i).index_max() + 1;
}
arma::vec Cell_est(total_cell_num);
for (int C_i = 0; C_i < total_cell_num; C_i++) {
Cell_est(C_i) = Cell_save.col(C_i).index_max() + 1;
}
return List::create(Named("subject_subgroup_label")=S_est, Named("cell_type_label")=Cell_est, Named("cell_type_effects")=mu_save, Named("subject_subgroup_effects")=beta_save, Named("cell_type_prop")=Pi_save,
Named("sigma_sq")=sigma_sq_save, Named("lam0")=lam0_save, Named("lam1")=lam1_save,
// Named("eta_mu")=eta_mu_save, Named("tau_sq_mu")=tau_sq_mu_save, Named("eta_beta")=eta_beta_save, Named("tau_sq_beta")=tau_sq_beta_save,
Named("alpha")=alpha_save, Named("subject_subgroup_prop")=phi_save);
}
}
}
// [[Rcpp::export]]
arma::mat update_mu_R(arma::mat theta_t, arma::mat beta_t, arma::vec sigma_sq_t, arma::vec clas_cell_t, arma::uvec S_vec_t,
const int K, const int G, double eta_mu, double tau_sq_mu) {
arma::mat mu_updated(G, K, fill::zeros);
for (int k = 0; k < K; k++) {
arma::vec tmp1(G, fill::zeros);
double tmp2 = 0;
arma::uvec ind_k = arma::find(clas_cell_t == (k+1));
if (ind_k.n_elem > 0) {
arma::uvec S_k = S_vec_t(ind_k);
tmp1 = arma::sum(theta_t.rows(ind_k).t() - beta_t.cols(S_k-1), 1);
tmp2 = ind_k.n_elem;
}
arma::vec avg = (tmp1/sigma_sq_t + eta_mu/tau_sq_mu)/(tmp2/sigma_sq_t + 1.0/tau_sq_mu);
arma::vec sd = sqrt(1.0/(tmp2/sigma_sq_t + 1.0/tau_sq_mu));
for (int i = 0; i < G; i++){
mu_updated(i,k) = R::rnorm(avg(i), sd(i));
}
}
return mu_updated;
}
// [[Rcpp::export]]
arma::mat update_Pi_R(arma::uvec clas_cell_t, arma::vec S_vec_t, arma::vec xi_vec_t, double gam, const int L, const int K) {
arma::vec xi_gamma = xi_vec_t * gam;
arma::mat tmp(K, L, fill::none);
for (int ell = 0; ell < L; ell++) {
arma::vec tmp0(K, fill::zeros);
arma::uvec ind_ell = arma::find(S_vec_t == (ell+1));
if (ind_ell.n_elem > 0) {
arma::uvec clas_cell_ell = clas_cell_t(ind_ell);
for (int k = 0; k < K; k++) {
arma::uvec ind_j = arma::find(clas_cell_ell == (k+1));
tmp0(k) = ind_j.n_elem;
}
}
tmp.col(ell) = rDirichlet(tmp0+xi_gamma);
}
return tmp;
}
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "../interpreter.h"
#include "standard.h"
#include "reference.h"
using namespace std;
void init_io(map<string, NFunction*> &native) {
native["write"] = new NFunction(&write);
native["get_i"] = new NFunction(&::get_int);
native["get_r"] = new NFunction(&::get_real);
native["get_s"] = new NFunction(&::get_string);
}
void init_arithmetic(map<string, NFunction*> &native) {
native["+"] = new NFunction(&::plus);
native["-"] = new NFunction(&::moins);
native["="] = new NFunction(&::egal);
native["<"] = new NFunction(&::less);
native["typeof"] = new NFunction(&::type);
native["rand"] = new NFunction(&::random);
}
Val write(Env* e, Store* s, vector<Expression*> args, int line, string file) {
for(unsigned int i = 0; i < args.size(); i++) {
Val v = rtov(args[i]->eval(s,e), s);
cout << v.to_s();
cout << " ";
}
cout << endl;
return Val(1);
}
Val simplePlus(Val arg1, Val arg2) {
int type1 = arg1.getType();
int type2 = arg2.getType();
if(type1 ==INTEGER && type2 == INTEGER) {
int i = arg1.to_i() + arg2.to_i();
return Val(i);
}
if((type1 == INTEGER && type2 == REAL) || (type2 == INTEGER && type1 == REAL) || (type1 == REAL && type2 == REAL)) {
double i = arg1.to_f() + arg2.to_f();
return Val(i);
}
if(type1 == STRING || type2 == STRING) {
string i = arg1.to_s() + arg2.to_s();
return Val(i);
}
return Val(1);
}
Val plus(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() < 2) {
cout << "cannot use operator + for less then 2 arguments" << endl << "\t at line " << line << " in file " << file << endl;
exit(1);
}
Val v1 = rtov(args[0]->eval(s,e), s);
Val v2 = rtov(args[1]->eval(s,e), s);
Val result = simplePlus(v1,v2);
for(unsigned int i = 2; i < args.size(); i++) {
Val v = rtov(args[i]->eval(s,e), s);
result = simplePlus(result, v);
}
return result;
}
Val moins(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() != 2) {
cout << "cannot use operator - for less or more then 2 arguments" << endl;
exit(1);
}
Val v1 = rtov(args[0]->eval(s,e), s);
Val v2 = rtov(args[1]->eval(s,e), s);
int type1 = v1.getType();
int type2 = v2.getType();
if(type1 ==INTEGER && type2 == INTEGER) {
int i = v1.to_i() - v2.to_i();
return Val(i);
}
if((type1 == INTEGER && type2 == REAL) || (type2 == INTEGER && type1 == REAL) || (type1 == REAL && type2 == REAL)) {
double i = v1.to_f() - v2.to_f();
return Val(i);
}
return Val(0);
}
Val egal(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() != 2) {
cout << "cannot use operator = for less then 2 arguments" << endl;
exit(1);
}
Val v1 = args[0]->eval(s,e);
Val v2 = args[1]->eval(s,e);
int type1 = v1.getType();
int type2 = v2.getType();
if(type1 == type2) {
if(type1 ==INTEGER) {
int i = v1.to_i() == v2.to_i();
return Val(i);
}
if(type1 == STRING) {
int i = v1.to_s() == v2.to_s();
return Val(i);
}
}
if((type1 == INTEGER && type2 == REAL) || (type2 == INTEGER && type1 == REAL) || (type1 == REAL && type2 == REAL)) {
int i = v1.to_f() == v2.to_f();
return Val(i);
}
return Val(0);
}
Val less(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() != 2) {
cout << "cannot use operator < for less or more then 2 arguments" << endl;
exit(1);
}
Val v1 = args[0]->eval(s,e);
Val v2 = args[1]->eval(s,e);
int type1 = v1.getType();
int type2 = v2.getType();
if(type1 == type2) {
if(type1 ==INTEGER) {
int i = v1.to_i() < v2.to_i();
return Val(i);
}
}
if((type1 == INTEGER && type2 == REAL) || (type2 == INTEGER && type1 == REAL) || (type1 == REAL && type2 == REAL)) {
int i = v1.to_f() < v2.to_f();
return Val(i);
}
return Val(0);
}
Val type(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() != 1) {
cout << "cannot use operator typeof for more then 1 arguments" << endl;
exit(1);
}
Val v1 = args[0]->eval(s,e);
int type1 = v1.getType();
if(type1 ==INTEGER) {
return Val("int");
}
if(type1 ==STRING) {
return Val("string");
}
if(type1 ==REAL) {
return Val("real");
}
if(type1 ==REFERENCE) {
return Val("ref");
}
if(type1 ==ARRAY) {
return Val("list");
}
return Val("empty");
}
Val get_int(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() > 0) {
cout << "input function doesn't take any argument" << endl;
exit(1);
}
int a = 0;
cin >> a;
return Val(a);
}
Val get_real(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() > 0) {
cout << "input function doesn't take any argument" << endl;
exit(1);
}
double a = 0;
cin >> a;
return Val(a);
}
Val get_string(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() > 0) {
cout << "input function doesn't take any argument" << endl;
exit(1);
}
string a = "";
cin >> a;
return Val(a);
}
Val random(Env* e, Store* s, vector<Expression*> args, int line, string file) {
if(args.size() != 1) {
cout << "rand take only one arg" << endl;
exit(1);
}
srand(time(NULL));
Val v1 = args[0]->eval(s,e);
if(v1.getType() ==INTEGER) {
return Val(rand() % (v1.to_i() + 1));
}
if(v1.getType() ==REAL) {
double r = rand();
return r / RAND_MAX * v1.to_f();
}
return Val();
}
|
#include <iostream>
using namespace std;
int display(int (*arr)[3]){
return *(*arr + 1);
}
int main() {
int arr[3][3] = {1,2,3,4,5,6,7,8,9};
int * p = *arr;
cout << *(*arr + 1) << endl;
cout << "===============" << endl;
cout << display(arr) << endl;
return 0;
}
|
#pragma once
class UdpDealer;
class HVDev;
typedef boost::shared_ptr<boost::asio::deadline_timer> TimerPtr;
class AsyncIO : public FGST<AsyncIO>
{
static boost::asio::io_service _ioService;
boost::shared_ptr<boost::asio::deadline_timer> _timer;
boost::asio::ip::udp::resolver _resolver;
public:
boost::shared_ptr<UdpDealer> _udp;
boost::shared_ptr<HVDev> _hvdev;
struct
{
short node_udp_port;
short cxx_udp_port;
} _cfg;
// std::shared_ptr<UdpServer> m_udpServer;
public:
int schedule_task(float seconds, std::function<int()> dealer);
int post_udp(const std::string& data);
void run();
void stop();
void init(const std::string& cfg);
TimerPtr get_timer(float second);
AsyncIO();
~AsyncIO();
private:
void routine(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* t );
void task_wrapper(const boost::system::error_code& /*e*/, boost::asio::deadline_timer* t, std::function<int()> dealer );
};
|
#ifndef GREEDY_THINKER_H_INCLUDED
#define GREEDY_THINKER_H_INCLUDED
#include "tracker_thinker.h"
struct GreedyThinker final : TrackerThinker
{
protected:
Response decideResponse(int guess) const override;
};
#endif // GREEDY_THINKER_H_INCLUDED
|
vector<int> solution(string &S, vector<int> &P, vector<int> &Q) {
// write your code in C++14 (g++ 6.2.0)
vector<int> A((S.length()+1), 0);
vector<int> C((S.length()+1), 0);
vector<int> G((S.length()+1), 0);
vector<int> T((S.length()+1), 0);
for (size_t i =0; i<S.length(); i++){
//cout << "S[i] = " << S[i] << endl;
A[i+1]=(S[i]=='A')? (A[i]+1): A[i];
C[i+1]=(S[i]=='C')? (C[i]+1): C[i];
G[i+1]=(S[i]=='G')? (G[i]+1): G[i];
T[i+1]=(S[i]=='T')? (T[i]+1): T[i];
}
vector<int> sol(P.size(), 0);
for (size_t j =0; j<P.size(); j++){
//cout << C[Q[j]+1] << "-" << C[P[j]] << endl;
if ((A[Q[j]+1]-A[P[j]])>0) sol[j]=1;
else if ((C[Q[j]+1]-C[P[j]])>0) sol[j]=2;
else if ((G[Q[j]+1]-G[P[j]])>0) sol[j]=3;
else if ((T[Q[j]+1]-T[P[j]])>0) sol[j]=4;
}
return sol;
}
|
// Copyright 2018 Benjamin Bader
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CPPMETRICS_METRICS_REGISTRY_H
#define CPPMETRICS_METRICS_REGISTRY_H
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <shared_mutex>
#include <string>
namespace cppmetrics {
class Gauge;
class Counter;
class Meter;
class Histogram;
class Timer;
class Registry
{
public:
std::shared_ptr<Gauge> gauge(const std::string& name);
std::shared_ptr<Counter> counter(const std::string& name);
std::shared_ptr<Meter> meter(const std::string& name);
std::shared_ptr<Histogram> histogram(const std::string& name);
std::shared_ptr<Timer> timer(const std::string& name);
std::map<std::string, std::shared_ptr<Gauge>> get_gauges();
std::map<std::string, std::shared_ptr<Counter>> get_counters();
std::map<std::string, std::shared_ptr<Meter>> get_meters();
std::map<std::string, std::shared_ptr<Histogram>> get_histograms();
std::map<std::string, std::shared_ptr<Timer>> get_timers();
private:
template <typename T, typename Factory>
std::shared_ptr<T> get_or_add(
const std::string& name,
std::map<std::string, std::shared_ptr<T>>& collection,
Factory&& factory);
private:
std::shared_timed_mutex m_mutex;
std::set<std::string> m_names;
std::map<std::string, std::shared_ptr<Gauge>> m_gauges;
std::map<std::string, std::shared_ptr<Counter>> m_counters;
std::map<std::string, std::shared_ptr<Meter>> m_meters;
std::map<std::string, std::shared_ptr<Histogram>> m_histograms;
std::map<std::string, std::shared_ptr<Timer>> m_timers;
};
template <typename T, typename Factory>
std::shared_ptr<T> Registry::get_or_add(
const std::string& name,
std::map<std::string, std::shared_ptr<T>>& collection,
Factory&& factory)
{
{ // scope for RAII shared-read lock
std::shared_lock<std::shared_timed_mutex> read_lock(m_mutex);
if (m_names.find(name) != m_names.end())
{
return collection[name];
}
}
std::unique_lock<std::shared_timed_mutex> lock(m_mutex);
if (m_names.find(name) != m_names.end())
{
return collection[name];
}
else
{
std::shared_ptr<T> metric = factory();
m_names.insert(name);
collection[name] = metric;
return metric;
}
}
} // namespace cppmetrics
#endif
|
#include <iostream>
#include <cstring>
using namespace std;
int main() {
/*
* char* arr = {'a'};
char* arr2 = "abcd";
int iValue = 10;
int* ptr = {1,2,3,4};
*/
const char * charArray = "abcde";
charArray = "tuyr";
*charArray = 'o'; // run time error
cout << *charArray << endl;
cout << charArray << endl;
cout << charArray+1 << endl;
char cArray[5] = {'s', 'w', 'a', '\0', 'd'};
cout << strlen(cArray) << endl;
const char* charPointer = cArray;
charPointer[0] = 't';
cout << charPointer << endl;
const char arr2[10] = "hello"; // may be array of constant characters
arr2[0] = 'a';
char* charArray2 = (char*)"StringLiteral";
const char* string1 = "StringOne";
char* string2 = string1;
char const charArray3[] = {'a', 'b'};
char charArray4[5] = "abc";
char const* ptr = &charArray3[0];
char* charArray5 = charArray4;
const char charArray6[5] = "art";
char charArray7[5] = "mus";
int arr[5] = {1,2,3,4,5};
int* ptrToArr = {1,2,3,4,5};
// int arr3[5] = arr; // array initializer must be an initializer list. unless it will give me error(if list is not used)
return 0;
}
|
// Copyright (c) 2021 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BinTools_ShapeWriter_HeaderFile
#define _BinTools_ShapeWriter_HeaderFile
#include <BinTools_ShapeSetBase.hxx>
#include <BinTools_OStream.hxx>
#include <NCollection_Map.hxx>
#include <TopTools_ShapeMapHasher.hxx>
class Geom_Curve;
class Geom2d_Curve;
class Geom_Surface;
class Poly_Polygon3D;
class Poly_PolygonOnTriangulation;
class Poly_Triangulation;
//! Writes topology in OStream in binary format without grouping of objects by types
//! and using relative positions in a file as references.
class BinTools_ShapeWriter : public BinTools_ShapeSetBase
{
public:
DEFINE_STANDARD_ALLOC
//! Builds an empty ShapeSet.
//! Parameter <theWithTriangles> is added for XML Persistence
Standard_EXPORT BinTools_ShapeWriter();
Standard_EXPORT virtual ~BinTools_ShapeWriter();
//! Clears the content of the set.
Standard_EXPORT virtual void Clear() Standard_OVERRIDE;
//! Writes the shape to stream using previously stored shapes and objects to refer them.
Standard_EXPORT virtual void Write (const TopoDS_Shape& theShape, Standard_OStream& theStream) Standard_OVERRIDE;
//! Writes location to the stream (all the needed sub-information or reference if it is already used).
Standard_EXPORT virtual void WriteLocation (BinTools_OStream& theStream, const TopLoc_Location& theLocation);
private:
//! Writes shape to the stream (all the needed sub-information or reference if it is already used).
virtual void WriteShape (BinTools_OStream& theStream, const TopoDS_Shape& theShape);
//! Writes curve to the stream (all the needed sub-information or reference if it is already used).
void WriteCurve (BinTools_OStream& theStream, const Handle(Geom_Curve)& theCurve);
//! Writes curve2d to the stream (all the needed sub-information or reference if it is already used).
void WriteCurve (BinTools_OStream& theStream, const Handle(Geom2d_Curve)& theCurve);
//! Writes surface to the stream.
void WriteSurface (BinTools_OStream& theStream, const Handle(Geom_Surface)& theSurface);
//! Writes ploygon3d to the stream.
void WritePolygon (BinTools_OStream& theStream, const Handle(Poly_Polygon3D)& thePolygon);
//! Writes polygon on triangulation to the stream.
void WritePolygon (BinTools_OStream& theStream, const Handle(Poly_PolygonOnTriangulation)& thePolygon);
//! Writes triangulation to the stream.
void WriteTriangulation (BinTools_OStream& theStream, const Handle(Poly_Triangulation)& theTriangulation,
const Standard_Boolean theNeedToWriteNormals);
/// position of the shape previously stored
NCollection_DataMap<TopoDS_Shape, uint64_t, TopTools_ShapeMapHasher> myShapePos;
NCollection_DataMap<TopLoc_Location, uint64_t> myLocationPos;
NCollection_DataMap<Handle(Geom_Curve), uint64_t> myCurvePos;
NCollection_DataMap<Handle(Geom2d_Curve), uint64_t> myCurve2dPos;
NCollection_DataMap<Handle(Geom_Surface), uint64_t> mySurfacePos;
NCollection_DataMap<Handle(Poly_Polygon3D), uint64_t> myPolygon3dPos;
NCollection_DataMap<Handle(Poly_PolygonOnTriangulation), uint64_t> myPolygonPos;
NCollection_DataMap<Handle(Poly_Triangulation), uint64_t> myTriangulationPos;
};
#endif // _BinTools_ShapeWriter_HeaderFile
|
#pragma once
#include "../vector-all.h"
#include "provider.h"
#include <functional>
namespace sbg {
template <int n>
struct ComponentProvider {
ComponentProvider(Provider<Vector<n, double>> position, Provider<Vector<freedom(n), double>> orientation);
Vector<freedom(n), double> getOrientation() const;
Vector<n, double> getPosition() const;
private:
Provider<Vector<freedom(n), double>> _orientation;
Provider<Vector<n, double>> _position;
};
extern template struct ComponentProvider<2>;
extern template struct ComponentProvider<3>;
using ComponentProvider2D = ComponentProvider<2>;
using ComponentProvider3D = ComponentProvider<3>;
}
|
#ifndef TEST_H
#define TEST_H
#include "init.h"
#include <algorithm>
int tipp = 0;
float ress = 0;
void test(int *sentence, int *testPositionE1, int *testPositionE2, int len, int e1, int e2, int r1, float &res, float *r) {
int tip[dimensionC];
for (int i = 0; i < dimensionC; i++) {
int last = i * dimension * window;
int lastt = i * dimensionWPE * window;
float mx = -FLT_MAX;
for (int i1 = 0; i1 <= len - window; i1++) {
float res = 0;
int tot = 0;
int tot1 = 0;
for (int j = i1; j < i1 + window; j++) {
int last1 = sentence[j] * dimension;
for (int k = 0; k < dimension; k++) {
res += matrixW1[last + tot] * wordVec[last1+k];
tot++;
}
int last2 = testPositionE1[j] * dimensionWPE;
int last3 = testPositionE2[j] * dimensionWPE;
for (int k = 0; k < dimensionWPE; k++) {
res += matrixW1PositionE1[lastt + tot1] * positionVecE1[last2+k];
res += matrixW1PositionE2[lastt + tot1] * positionVecE2[last3+k];
tot1++;
}
}
if (res > mx) mx = res;
}
r[i] = mx + matrixB1[i];
}
for (int i = 0; i < dimensionC; i++)
r[i] = CalcTanh(r[i]);
float s2 = -FLT_MAX;
int r2;
for (int i = 0; i < dimensionC; i++)
r[i] = CalcTanh(r[i]);
for (int j = 1; j < relationTotal; j++) {
float s = 0;
for (int i = 0; i < dimensionC; i++)
s += matrixRelation[j * dimensionC + i] * r[i];
if (s >= s2) {
s2 = s;
r2 = j;
}
}
tipp = r2;
if (s2 < 0) tipp = 0;
ress = s2;
}
float mxx = 0;
struct arr {
int num;
int ans;
float res;
};
arr work[100000];
struct cmp {
bool operator()(const arr &a,const arr&b) {
return a.res>b.res;
}
};
void test() {
float *matrixW1Dao = (float*)calloc(dimensionC * dimension * window, sizeof(float));
float *matrixB1Dao = (float*)calloc(dimensionC, sizeof(float));
float *r = (float *)calloc(dimensionC, sizeof(float));
std::vector<int> ans;
float res = 0;
int re1 = testtrainLists.size();
ans.clear();
int tot=0;
for (int k1 = 0; k1 < re1; k1++) {
int i=k1;
test(testtrainLists[i], testPositionE1[i], testPositionE2[i], testtrainLength[i], testheadList[i], testtailList[i], testrelationList[i], res, r);
work[tot].num = 8001+k1;
work[tot].ans = tipp;
work[tot].res = ress;
tot++;
}
res = 0;
float mxxx=0;
for (int i = 0; i <tot;i++) {
if (work[i].ans==0) continue;
if (work[i].ans == testrelationList[work[i].num-8001]) res+=1;
mxxx+=1;
}
mxxx = res / mxxx;
float mxxy = res / 2263;
mxxx = 2/((1/mxxx)+(1/mxxy));
printf("%.6f\n: ",mxxx);
if (mxxx>mxx) {
mxx=mxxx;
FILE *out=fopen("out/output.txt","w");
for (int i=re1-1;i>=0;i--)
fprintf(out, "%d %s\n", work[i].num, nam[work[i].ans].c_str());
fclose(out);
}
free(matrixW1Dao);
free(matrixB1Dao);
free(r);
}
#endif
|
/* -*- coding: utf-8 -*-
!@time: 2020/3/2 12:58
!@author: superMC @email: 18758266469@163.com
!@fileName: findIf_func.cpp
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
using namespace std;
struct C {
C() : v1(0), v2(0) {}
C(const int &val1, const int &val2) : v1(val1), v2(val2) {
}
C operator()(const int &val1, const int &val2) { //重载构造方法
v1 = val1;
v2 = val2;
return *this;
}
~C() = default;
int v1;
int v2;
};
template<int n> //只能传入常数
class CComp {
public:
bool operator()(const C &lhs) {
return (lhs.v2 == n);
}
};
int fun(int argc, char *argv[]) {
vector<C> cv;
C val;
C c(1, 2);
cv.emplace_back(0, 10);
cv.push_back(val(1, 100));
cv.push_back(val(2, 52));
cv.push_back(val(3, 25));
cv.push_back(val(4, 75));
cv.push_back(val(5, 84));
cv.push_back(val(6, 33));
auto cvIter = find_if(cv.begin(), cv.end(), CComp<75>());
cout << cvIter->v1 << " " << cvIter->v2 << endl;
cout << endl;
system("PAUSE");
return 0;
}
|
#pragma once
#include "EverydayTools/Exception/CallAndRethrow.h"
#include "EverydayTools/Exception/ThrowIfFailed.h"
#include "Keng/Base/Serialization/Serialization.h"
#include "yasli/Archive.h"
namespace keng
{
template<typename T>
inline void SerializeMandatory(Archive& ar, T& val, const char* name = "") {
CallAndRethrowM + [&] {
edt::ThrowIfFailed(ar(val, name), "Failed to parse mandatory field \"", name, "\"");
};
}
}
|
#pragma once
#include <QMutex>
#include <QMap>
#include <QPoint>
#include "Bubble.h"
class BubbleManager: public QObject
{
Q_OBJECT
public:
BubbleManager(QWidget* parent = Q_NULLPTR);
~BubbleManager();
Bubble* addBubble();
void lock();
void unlock();
public slots:
void removeBubble(Bubble& bubble);
public:
QMap<Bubble*, QPoint> bubbles;
private:
QMutex mutex;
QWidget* parentWidget;
};
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> soliDatos() ;
int factorial( int ) ;
vector<int> burbuja( vector<int> ) ;
void mostrarVector( vector<int> ) ;
int main()
{
vector<int> lista ;
int valor = 0 ;
lista = soliDatos() ;
cout << "Numeros ingresados: " ; mostrarVector( lista ) ;
lista = burbuja( lista ) ;
cout << "Lista ordenada: " ; mostrarVector( lista ) ;
valor = factorial( lista.at( 0 ) ) ;
cout << "El factorial es: " << valor << endl ;
return 0 ;
} // fin main
vector<int> soliDatos()
{
vector<int> lista;
int valor = 0 ;
for( int i = 0 ; i < 5 ; i++ )
{
cout << "Ingrese numero: " ; cin >> valor ;
lista.push_back( valor ) ;
}
return lista ;
} // fin soliDatos
int factorial( int valor )
{
if( valor == 0 ) return 1 ;
else return valor * factorial( valor - 1 ) ;
} // fin factorial
vector<int> burbuja( vector<int> lista )
{
sort( lista.begin() , lista.end() ) ;
return lista ;
} // fin ordenarMenorManyor
void mostrarVector( vector<int> lista )
{
for( int i = 0 ; i < lista.size() ; i++ )
{
if( i == lista.size() - 1 ) cout << lista.at(i) << endl ;
else cout << lista.at(i) << " " ;
}
} // fin mostrarVector
|
#include "stdafx.h"
#include "../EditTool.h"
#include "../Editor.h"
#include "../Resource.h"
#include "../TerrainPaintDialog.h"
#include "TerrainPaintTool.h"
IMPLEMENT_DYNCREATE(CTerrainPaintTool, CEditTool)
CTerrainPaintTool::CTerrainPaintTool()
: mBrushType(E_TERRAIN_PAINT_NULL_TYPE),
mbBeginEdit(false),
mBrushSize(0.02f),
mHeightUpdateCountDown(0),
mTimeLastFrame(0),
mBrushHardness(0.001f),
mLayerEdit(0)
{
m_iCurrentPageId = 0;
m_pTerrainCtrl = GetEditor()->GetRollupCtrl(E_TERRAIN_CTRL);
mName = "地表绘制工具";
}
CTerrainPaintTool::~CTerrainPaintTool()
{
}
void CTerrainPaintTool::BeginTool()
{
// TODO: 在此添加控件通知处理程序代码
m_iCurrentPageId = m_pTerrainCtrl->InsertPage("绘制地形表面", IDD_TERRAIN_PAINT_DIALOG, RUNTIME_CLASS(CTerrainPaintDialog), 2);
m_pTerrainCtrl->ExpandPage(m_iCurrentPageId);
mEditDecal.Create( "DecalEdit", "DecalEdit", 16 );
//mEditDecal.SetScale( mBrushSize*TERRAIN_WORLD_SIZE * 0.5f );
// Update terrain at max 20fps
mHeightUpdateRate = 50;
mTimeLastFrame = Ogre::Root::getSingletonPtr()->getTimer()->getMilliseconds();
}
void CTerrainPaintTool::EndTool()
{
// TODO: 在此添加控件通知处理程序代码
if ( m_iCurrentPageId )
{
m_pTerrainCtrl->RemovePage(m_iCurrentPageId);
}
mEditDecal.Destroy();
}
void CTerrainPaintTool::Update()
{
unsigned long newTime = Ogre::Root::getSingletonPtr()->getTimer()->getMilliseconds();
unsigned long timeSinceLastFrame = newTime - mTimeLastFrame;
if (mHeightUpdateCountDown > 0)
{
mHeightUpdateCountDown -= timeSinceLastFrame;
if (mHeightUpdateCountDown <= 0)
{
GetEditor()->GetTerrainGroup()->update();
mHeightUpdateCountDown = 0;
}
}
mTimeLastFrame = newTime;
}
void CTerrainPaintTool::OnLButtonDown(UINT nFlags, CPoint point)
{
mbBeginEdit = true;
}
void CTerrainPaintTool::OnLButtonUp(UINT nFlags, CPoint point)
{
mbBeginEdit = false;
}
void CTerrainPaintTool::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
//处理键盘响应
switch(nChar)
{
//esc键
case VK_ESCAPE:
{
}
break;
case VK_LEFT:
break;
case VK_RETURN:
break;
}
}
void CTerrainPaintTool::OnMouseMove(UINT nFlags, CPoint point)
{
Ogre::TerrainGroup::RayResult rayResult = GetEditor()->TerrainHitTest( point );
if (rayResult.hit)
{
mEditDecal.setPosition(rayResult.position.x, rayResult.position.z, 2.0f);
if ( mBrushType == E_TERRAIN_PAINT_NULL_TYPE )
return;
if ( mLayerEdit == 0 )
return;
if ( mbBeginEdit )
{
// figure out which terrains this affects
TerrainGroup::TerrainList terrainList;
Real brushSizeWorldSpace = TERRAIN_WORLD_SIZE * mBrushSize;
Sphere sphere(rayResult.position, brushSizeWorldSpace);
GetEditor()->GetTerrainGroup()->sphereIntersects(sphere, &terrainList);
for (TerrainGroup::TerrainList::iterator it = terrainList.begin();
it != terrainList.end(); ++it)
{
Terrain* terrain = *it;
Vector3 tsPos;
terrain->getTerrainPosition(rayResult.position, &tsPos);
TerrainLayerBlendMap* layer = terrain->getLayerBlendMap(mLayerEdit);
// we need image coords
Real imgSize = terrain->getLayerBlendMapSize();
long startx = (tsPos.x - mBrushSize) * imgSize;
long starty = (tsPos.y - mBrushSize) * imgSize;
long endx = (tsPos.x + mBrushSize) * imgSize;
long endy= (tsPos.y + mBrushSize) * imgSize;
startx = std::max(startx, 0L);
starty = std::max(starty, 0L);
endx = std::min(endx, (long)imgSize);
endy = std::min(endy, (long)imgSize);
for (long y = starty; y <= endy; ++y)
{
for (long x = startx; x <= endx; ++x)
{
Real tsXdist = (x / imgSize) - tsPos.x;
Real tsYdist = (y / imgSize) - tsPos.y;
Real weight = std::min((Real)1.0,
Math::Sqrt(tsYdist * tsYdist + tsXdist * tsXdist) / Real(0.5 * mBrushSize));
weight = 1.0 - (weight * weight);
float paint = weight * mBrushHardness;
size_t imgY = imgSize - y;
float val;
switch( mBrushType )
{
case E_TERRAIN_ADD:
{
val = layer->getBlendValue(x, imgY) + paint;
}
break;
case E_TERRAIN_MINUS:
{
val = layer->getBlendValue(x, imgY) - paint;
}
break;
}
val = Math::Clamp(val, 0.0f, 1.0f);
layer->setBlendValue(x, imgY, val);
}
}
layer->update();
}
if (mHeightUpdateCountDown == 0)
mHeightUpdateCountDown = mHeightUpdateRate;
}
}
}
void CTerrainPaintTool::SetBrushHardness( Real hardness )
{
mBrushHardness = hardness;
}
void CTerrainPaintTool::SetBrushSize( Real brushSize )
{
mBrushSize = brushSize;
mEditDecal.SetScale( mBrushSize*TERRAIN_WORLD_SIZE * 0.5f );
}
void CTerrainPaintTool::SetBrushType( E_TERRAIN_PAINT_TYPE type )
{
mBrushType = type;
}
void CTerrainPaintTool::SetLayerEdit( uint8 layerId )
{
mLayerEdit = layerId;
}
|
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
struct path
{
int dest;
double time;
};
struct node
{
double shortest;
int pred;
bool flag;
path link[8];
};
struct stop
{
int index;
stop *next;
};
struct chromosome
{
stop *route[11];
double num_of_bus[11];
double total_trip_time[11];
double Objective;
bool direct_service[24][30];
};
void inputnetwork(node TSW_stop[], int terminal_list[], int destination_list[], const int num_of_terminal, const int num_of_destination, int demand[][30]);
double Dijkstra(node TSW_stop[], int origin, int destination);
void initialsolution(stop* route[],node* TSW_stop,const int num_of_terminal,const int num_of_destination,int terminal_list[], int destination_list[], const int Route_max, const int Time_max, const int Stop_max, double shortest_time_matrix[][30]);
void add2end(stop*& ptr, int x);
void displayallroute(stop* route[],const int Route_max);
void delist (stop* ptr[],const int Route_max);
void deepCopy(stop* ptr, stop*& copy);
bool exist(int x, stop* ptr);
int length(stop* ptr); // Total stop (include origin and destination)
void InsertAtPos(int pos, stop*& ptr, int randx); // pos, that route, stop
double Calculate_Total_Route_Time_on_TSW(int num_of_inter_stop, stop* ptr, double shortest_time_matrix[][30]);
void del(stop*& ptr, int key);
void replace_node(stop*& ptr, stop* ptr2, int key,int new_node, bool& flag_replace, double shortest_time_matrix[][30], const double Time_max); // Change key to new_node // Do repairing for 1 node only
void Calculate_Total_trip_time(double& total_trip_time, stop* ptr, double shortest_time_matrix[][30]);
void Update_frequency_setting(stop* route[], double num_of_bus[],double total_trip_time[],double& Objective,bool direct_service[][30],int demand[][30],double shortest_time_matrix[][30],const int Route_max); // Update for 1 gene
void Crossover_route(chromosome Parent1,chromosome Parent2, chromosome& Child1, chromosome& Child2);
void Crossover_stop(chromosome Parent1,chromosome Parent2, chromosome& Child1, chromosome& Child2, double shortest_time_matrix[][30]);
void deepCopy_start_from(stop* ptr, stop*& copy, int start_from, int numofnodes, int count_node);
void deepCopy_numofnodes(stop* ptr,stop*& copy,int numofnodes, int count_node2);
void check_repeated_node(stop* ptr, int& repeated_node);
void Mutation_insert(stop* route[]);
void Mutation_remove(stop* route[]);
void Mutation_swap(stop* route[]);
void Mutation_transfer(stop* route[]);
void stop_sequence_improvement(chromosome& Child,double shortest_time_matrix[][30], const int Route_max);
void check_repair(chromosome& Child,double shortest_time_matrix[][30], const int Route_max);
void repair_operator(stop*& ptr,double shortest_time_matrix[][30]);
void repair_missing(chromosome& Child,double shortest_time_matrix[][30], const int Route_max, const double Time_max);
void del_gene(chromosome& parent, const int Route_max);
void deepCopy_gene(chromosome parent, chromosome& copy, const int Route_max);
void Diversity_control(chromosome gene[], const int Route_max);
int main()
{
clock_t start = clock();
const int num_of_terminal = 7, num_of_destination = 5;
const int Route_max = 10;
const double Time_max = 35;
const int Stop_max = 8;
srand(time(NULL));
int terminal_list[num_of_terminal+1];
int destination_list[num_of_destination+1];
node TSW_stop[30];
double shortest_time_matrix[30][30];
int demand[24][30];
// Initialization
for (int i=1;i<=29;i++)
{
TSW_stop[i].shortest = 9999;
TSW_stop[i].pred = 0;
TSW_stop[i].flag = false;
for (int j=1;j<8;j++)
{
TSW_stop[i].link[j].dest = -1;
TSW_stop[i].link[j].time = 0;
}
}
// Input the network from txt file
inputnetwork(TSW_stop,terminal_list,destination_list,num_of_terminal,num_of_destination,demand);
cout << "demand:" << endl;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
cout << demand[i][j] << " ";
cout << endl;
}
// Calculate shortest_time_matrix
for (int i=1;i<=29;i++)
for (int j=1;j<=29;j++)
shortest_time_matrix[i][j] = Dijkstra(TSW_stop,i,j);
// Randomly generate 20 initial solutions
chromosome gene[41];
for (int i=1;i<=20;i++)
{
for (int j=1;j<=Route_max;j++)
gene[i].route[j] = new stop;
initialsolution(gene[i].route,TSW_stop,num_of_terminal,num_of_destination,terminal_list,destination_list,Route_max,Time_max,Stop_max,shortest_time_matrix);
for (int j=1;j<=Route_max;j++)
{
gene[i].total_trip_time[j] = 0;
Calculate_Total_trip_time(gene[i].total_trip_time[j],gene[i].route[j],shortest_time_matrix);
}
for (int j=1;j<=Route_max;j++)
{
if (j<=6)
gene[i].num_of_bus[j] = 18;
else
gene[i].num_of_bus[j] = 17;
}
}
// allocate optimal frequency setting
for (int i=1;i<=20;i++)
{
Update_frequency_setting(gene[i].route,gene[i].num_of_bus,gene[i].total_trip_time,gene[i].Objective,gene[i].direct_service,demand,shortest_time_matrix,Route_max);
}
// Display 20 genes
for (int i=1;i<=20;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl;
}
for (int iter = 1; iter <= 2000; iter++)
{
cout << endl << "Iteration: " << iter << endl;
int rand_num;
// Do route/stop crossover
for (int i=1;i<=19;i=i+2)
{
rand_num = rand()%2 + 1;
if (rand_num == 1)
{
cout << endl << "Do route crossover" << endl;
Crossover_route(gene[i],gene[i+1],gene[i+20],gene[i+1+20]);
}
if (rand_num == 2)
{
cout << endl << "Do stop crossover" << endl;
Crossover_stop(gene[i],gene[i+1],gene[i+20],gene[i+1+20],shortest_time_matrix);
}
}
// Display 40 genes (Parents + offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl;
}
// Do mutation
for (int i=21;i<=40;i++)
{
rand_num = rand()%10+1;
if (rand_num >=1 && rand_num <=4)
{
cout << endl << "gene[" << i << "] do insert " << endl;
Mutation_insert(gene[i].route);
}
if (rand_num >=5 && rand_num <=8)
{
cout << endl << "gene[" << i << "] do remove " << endl;
Mutation_remove(gene[i].route);
}
if (rand_num ==9)
{
cout << endl << "gene[" << i << "] do swap " << endl;
Mutation_swap(gene[i].route);
}
if (rand_num ==10)
{
cout << endl << "gene[" << i << "] do transfer " << endl;
Mutation_transfer(gene[i].route);
}
}
// Display 40 genes (Parents + offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl;
}
// Stop sequence improvement heuristic
for (int i=21;i<=40;i++)
{
cout << endl << "gene[" << i << "]: " << endl;
stop_sequence_improvement(gene[i],shortest_time_matrix,Route_max);
}
// Display 40 genes (Parents + offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl;
}
// Repair operator
for (int i=21;i<=40;i++)
{
cout << endl << "gene[" << i << "]: " << endl;
check_repair(gene[i],shortest_time_matrix,Route_max);
}
// Display 40 genes (Parents + offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl;
}
// Repair missing nodes (if missing nodes <= 1 -> repair, otherwise delete it)
for (int i=21;i<=40;i++)
{
cout << endl << "gene[" << i << "]: " << endl;
repair_missing(gene[i],shortest_time_matrix,Route_max,Time_max);
}
// Display 40 genes (Parents + offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl;
}
// allocate optimal frequency setting for childs
for (int i=21;i<=40;i++)
{
cout << endl << "gene[" << i << "]: optimal frequency2" << endl;
if (gene[i].route[1]->index != -1)
Update_frequency_setting(gene[i].route,gene[i].num_of_bus,gene[i].total_trip_time,gene[i].Objective,gene[i].direct_service,demand,shortest_time_matrix,Route_max);
else gene[i].Objective = 999999999;
}
// Display 40 genes (Parents + offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl << "Objective: " << gene[i].Objective << endl;
}
// Diversity control
cout << endl << "Diversity control" << endl;
Diversity_control(gene,Route_max);
// Check if the population = 20 // If not, initial solution
if (gene[20].route[1] == NULL)
{
for (int i=1;i<=20;i++)
{
if (gene[i].route[1] == NULL)
{
for (int j=1;j<=Route_max;j++)
gene[i].route[j] = new stop;
initialsolution(gene[i].route,TSW_stop,num_of_terminal,num_of_destination,terminal_list,destination_list,Route_max,Time_max,Stop_max,shortest_time_matrix);
for (int j=1;j<=Route_max;j++)
{
gene[i].total_trip_time[j] = 0;
Calculate_Total_trip_time(gene[i].total_trip_time[j],gene[i].route[j],shortest_time_matrix);
}
for (int j=1;j<=Route_max;j++)
{
if (j<=6)
gene[i].num_of_bus[j] = 18;
else
gene[i].num_of_bus[j] = 17;
}
Update_frequency_setting(gene[i].route,gene[i].num_of_bus,gene[i].total_trip_time,gene[i].Objective,gene[i].direct_service,demand,shortest_time_matrix,Route_max);
}
}
}
// Display 40 genes (Parents+ offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "gene[" << i << "] 10 routes:" << endl;
displayallroute(gene[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << gene[i].total_trip_time[j] << " ";
cout << endl << "Objective: " << gene[i].Objective << endl;
}
cout << endl << "Best objective in iteration " << iter << ": " << gene[1].Objective << endl;
}
clock_t end = clock();
double elapsed = double(end - start)/CLOCKS_PER_SEC;
cout << "Time measured: " << elapsed << "seconds." << endl;
return 0;
}
void inputnetwork(node TSW_stop[], int terminal_list[], int destination_list[], const int num_of_terminal, const int num_of_destination, int demand[][30])
{
ifstream fin;
int n, temp, num_of_path;
char dummy;
string line;
// Read txt file
fin.open("network.txt");
if (fin.fail())
{
cout << "Error opening txt file" << endl;
exit (1);
}
fin >> n;
getline(fin,line);
// read network
for (int i=1;i<=n;i++)
{
getline(fin, line);
fin >> temp;
fin >> dummy;
fin >> num_of_path;
getline(fin, line);
for (int j=1; j <= num_of_path;j++)
{
fin >> TSW_stop[i].link[j].dest;
fin >> dummy;
fin >> TSW_stop[i].link[j].time;
getline(fin, line);
}
}
getline(fin, line);
getline(fin, line);
// read terminal list and destination list
for (int i=1;i<=num_of_terminal;i++)
{
fin >> terminal_list[i];
fin >> dummy;
}
getline(fin, line);
getline(fin, line);
getline(fin, line);
for (int i=1;i<=num_of_destination;i++)
{
fin >> destination_list[i];
fin >> dummy;
}
getline(fin, line);
getline(fin, line);
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
fin >> demand[i][j] >> dummy;
getline(fin, line);
}
fin.close();
};
double Dijkstra(node TSW_stop[], int origin, int destination)
{
int Remaining_shortest, next;
double shortest_time;
for (int i=1; i<=29; i++)
{
TSW_stop[i].shortest = 9999;
TSW_stop[i].pred = 0;
TSW_stop[i].flag = false;
}
TSW_stop[origin].pred = 0;
TSW_stop[origin].shortest = 0;
// start finding the solution
for (int i=1;i<=29;i++)
{
shortest_time = 9999;
for (int j=1;j<=29;j++)
{
if (TSW_stop[j].flag == false)
{
if (TSW_stop[j].shortest <= shortest_time)
{
Remaining_shortest = j;
shortest_time = TSW_stop[j].shortest;
}
}
}
TSW_stop[Remaining_shortest].flag = true;
for (int j=1;j<=7;j++)
{
next = TSW_stop[Remaining_shortest].link[j].dest;
if (next != -1)
{
if (TSW_stop[next].flag == false)
{
if (TSW_stop[next].shortest > TSW_stop[Remaining_shortest].shortest + TSW_stop[Remaining_shortest].link[j].time)
{
TSW_stop[next].shortest = TSW_stop[Remaining_shortest].shortest + TSW_stop[Remaining_shortest].link[j].time;
TSW_stop[next].pred = Remaining_shortest;
}
}
}
}
}
return TSW_stop[destination].shortest;
};
void initialsolution(stop* route[],node* TSW_stop,const int num_of_terminal,const int num_of_destination,int terminal_list[], int destination_list[], const int Route_max, const int Time_max, const int Stop_max, double shortest_time_matrix[][30])
{
int check[30]; // For checking if all destination/stop exists
int randx; // variable for
bool flag = false; // For checking if all destination exists
bool flag_miss = false; // For checking if any stop missed
bool flag_repeat = true; // For checking if the stops already appear within that route
bool time_exceed = false;
int num_of_inter_stop = 0;
bool flag_replace;
int set_of_check0[24]; // For repairing
int set_of_check2[24]; // For repairing
int index_for_check0; // For repairing
int index_for_check2; // For repairing
double shortest_travel_time, travel_time_ABC;
double shortest_travel_time_for_repairing; // For repairing
int closest_node; // For repairing
int temp_shortest_pos;
stop* temp_ptr;
int count=0;
while (flag == false)
{
for (int j=1;j<= num_of_destination;j++)
check[j] = 0;
for (int i=1;i<=Route_max;i++)
{
// Randomly select a terminal node
randx = rand() % num_of_terminal + 1;
route[i]->index = terminal_list[randx];
route[i]->next = NULL;
// Randomly select a destination node
randx = rand() % num_of_destination + 1;
add2end(route[i],destination_list[randx]);
check[randx]++;
}
flag = true;
for (int j=1;j<= num_of_destination;j++)
{
if (check[j] == 0)
flag = false;
}
displayallroute(route,Route_max);
}
displayallroute(route,Route_max);
stop *temp[11];
for (int i=1;i<=Route_max;i++)
deepCopy(route[i],temp[i]);
while (flag_miss == false)
{
count++;
cout << "count: " << count << endl;
// Return back to origin and destination only
delist(route,Route_max);
for (int j=1;j<=Route_max;j++)
deepCopy(temp[j],route[j]);
displayallroute(route,Route_max);
// Initialization of check parameter (Check if any missed stops)
for (int j=1;j<= 23;j++)
check[j] = 0;
for (int j=1;j<= Route_max;j++)
{
check[route[j]->index]++;
}
for (int i=1;i<=Route_max;i++)
{
num_of_inter_stop = 0;
time_exceed = false;
// Inserting stop until one of the constraints is violated
while (time_exceed == false && num_of_inter_stop <= Stop_max)
{
flag_repeat = true;
// Randomly select a stop with no repeat
while (flag_repeat == true)
{
randx = rand()%23 + 1;
flag_repeat = exist(randx, route[i]);
}
cout << endl << "Finding the best position to insert Node" << randx << "." << endl;
// Find which position result in minimum travel time
shortest_travel_time = 9999;
for (int j=1;j<=length(route[i])-1;j++)
{
travel_time_ABC = 0;
temp_ptr = route[i];
for (int k=1;k<j;k++)
temp_ptr = temp_ptr -> next;
travel_time_ABC += shortest_time_matrix[temp_ptr->index][randx] + shortest_time_matrix[randx][temp_ptr->next->index] - shortest_time_matrix[temp_ptr->index][temp_ptr->next->index];
if (travel_time_ABC < shortest_travel_time)
{
shortest_travel_time = travel_time_ABC;
temp_shortest_pos = j;
}
}
InsertAtPos(temp_shortest_pos,route[i],randx);
check[randx]++;
displayallroute(route,Route_max);
num_of_inter_stop++;
cout << endl << "Number of inter stop:" << num_of_inter_stop << endl;
cout << endl << "Total time: " << Calculate_Total_Route_Time_on_TSW(num_of_inter_stop,route[i],shortest_time_matrix) << endl;
if (Calculate_Total_Route_Time_on_TSW(num_of_inter_stop,route[i],shortest_time_matrix) > Time_max)
{
time_exceed = true;
}
}
// Delete the latest node since it violates one of the constraints
del(route[i],randx);
check[randx]--;
}
flag_miss = true;
// Start repairing the randomly generate solution
// Replace the repeated nodes with missed nodes
// Find the repeated nodes which have the closest distance with the missed nodes
for (int j=1;j<= 23;j++)
{
set_of_check0[j] = 0;
set_of_check2[j] = 0;
}
index_for_check0 = 1;
index_for_check2 = 1;
for (int j=1;j<=23;j++)
{
if (check[j] == 0)
{
set_of_check0[index_for_check0] = j;
index_for_check0++;
}
if (check[j] > 1)
{
set_of_check2[index_for_check2] = j;
index_for_check2++;
}
}
// Debug
cout << endl;
for (int j=1;j<index_for_check0;j++)
{
cout << set_of_check0[j] << " ";
}
cout << endl;
for (int j=1;j<index_for_check2;j++)
{
cout << set_of_check2[j] << " ";
}
cout << endl;
//Debug
// Only repair if num of missed nodes <= 1
if (index_for_check0-1 <= 1)
{
for (int j=1;j<index_for_check0;j++)
{
shortest_travel_time_for_repairing = 9999;
closest_node = 99;
for (int k=1;k<index_for_check2;k++)
{
if (shortest_time_matrix[set_of_check0[j]][set_of_check2[k]] < shortest_travel_time_for_repairing)
{
shortest_travel_time_for_repairing = shortest_time_matrix[set_of_check0[j]][set_of_check2[k]];
closest_node = k;
}
}
flag_replace = false;
cout << "Closest node: " << set_of_check2[closest_node] << endl;
for (int a=1;a<=Route_max;a++)
{
replace_node(route[a]->next,route[a],set_of_check2[closest_node],set_of_check0[j],flag_replace,shortest_time_matrix,Time_max);
}
if (flag_replace == true)
{
check[set_of_check2[closest_node]]--;
check[set_of_check0[j]]++;
}
displayallroute(route,Route_max);
}
}
for (int j=1;j<= 23;j++)
{
if (check[j] == 0)
flag_miss = false;
}
}
};
void add2end(stop*& ptr, int x)
{
if (ptr == NULL)
{
ptr = new stop;
ptr -> index = x;
ptr -> next = NULL;
}
else
add2end(ptr->next,x);
}
void displayallroute(stop* route[],const int Route_max)
{
cout << endl << "Summary: "<< endl;
cout << "Route [i]: -> [Bus Terminal] -> [Intermediate stop 1] -> [Intermediate stop 2] -> ..." << endl;
stop *ptr;
cout << endl;
for (int i=1;i<=Route_max;i++)
{
cout << "Route " << i << ": ";
ptr = route[i];
while (ptr != NULL)
{
cout << "-> "<< ptr->index;
ptr = ptr->next;
}
cout << endl;
}
}
void delist (stop* ptr[],const int Route_max)
{
stop *temp;
for (int i=1; i<=Route_max;i++)
{
while (ptr[i] != NULL)
{
temp = ptr[i];
ptr[i] = ptr[i]->next;
delete temp;
}
}
for (int i=1; i<=Route_max;i++)
{
ptr[i] = NULL;
}
};
void deepCopy(stop* ptr, stop*& copy)
{
if (ptr != NULL)
{
copy = new stop;
copy->index = ptr->index;
copy->next = NULL;
deepCopy(ptr->next,copy->next);
}
}
bool exist(int x, stop* ptr)
{
while (ptr != NULL)
{
if (ptr->index == x)
return true;
else
ptr = ptr->next;
}
return false;
}
int length(stop* ptr)
{
int n=0;
while (ptr!= NULL)
{
n++;
ptr = ptr-> next;
}
return n;
}
void InsertAtPos(int pos, stop*& ptr, int randx)
{
stop *temp;
stop *temp2;
temp2 = ptr;
for (int i=1;i<pos;i++)
{
temp2 = temp2->next;
}
temp = new stop;
temp -> index = randx;
temp -> next = temp2 -> next;
temp2 -> next = temp;
}
double Calculate_Total_Route_Time_on_TSW(int num_of_inter_stop, stop* ptr, double shortest_time_matrix[][30])
{
const double s = 1.5;
double sum = 0;
stop* temp;
temp = ptr;
sum += num_of_inter_stop * s;
for (int i=1;i<=num_of_inter_stop;i++)
{
sum += shortest_time_matrix[temp->index][temp->next->index];
temp = temp->next;
}
sum += shortest_time_matrix[temp->index][29];
return sum;
}
void del(stop*& ptr, int key)
{
if (ptr != NULL)
{
if (ptr->index == key)
{
stop* temp;
temp = ptr;
ptr = ptr -> next;
delete temp;
}
else
del(ptr->next,key);
}
}
void replace_node(stop*& ptr, stop* ptr2, int key,int new_node, bool& flag_replace, double shortest_time_matrix[][30], const double Time_max)
{
if (ptr != NULL)
{
if (ptr->index == key && flag_replace == false)
{
ptr->index = new_node;
cout << endl << "TOtal time in TSW" << Calculate_Total_Route_Time_on_TSW(length(ptr2)-2,ptr2,shortest_time_matrix) << endl;
if (Calculate_Total_Route_Time_on_TSW(length(ptr2)-2,ptr2,shortest_time_matrix) < Time_max)
{
flag_replace = true;
}
else
ptr->index = key;
replace_node(ptr->next, ptr2, key, new_node, flag_replace, shortest_time_matrix, Time_max);
}
else
replace_node(ptr->next, ptr2, key, new_node, flag_replace, shortest_time_matrix, Time_max);
}
}
void Calculate_Total_trip_time(double& total_trip_time, stop* ptr, double shortest_time_matrix[][30])
{
const double s = 1.5;
total_trip_time = 0;
stop* temp;
temp = ptr;
while (temp->next != NULL)
{
total_trip_time = total_trip_time + s + shortest_time_matrix[temp->index][temp->next->index];
temp = temp->next;
}
total_trip_time -= s;
}
void Update_frequency_setting(stop* route[], double num_of_bus[],double total_trip_time[],double& Objective,bool direct_service[][30],int demand[][30],double shortest_time_matrix[][30], const int Route_max)
{
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
direct_service[i][j] = false;
}
stop* temp;
stop* temp2;
// See if there is any direct service
for (int i=1;i<=Route_max;i++)
{
// Find the destination
temp = route[i];
temp2 = route[i];
while (temp->next != NULL)
{
temp = temp->next;
}
// Turn each direct service to the above destination to true
while (temp2->next->next != NULL)
{
direct_service[temp2->index][temp->index] = true;
temp2 = temp2->next;
}
direct_service[temp2->index][temp->index] = true;
}
// debug
cout << endl << "direct_service_matrix" << endl;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
cout << direct_service[i][j] << " ";
}
// debug
double average_travel_time;
double nominator[24][30];
double nominator_tran1[24][30];
double denominator[24][30];
double denominator_tran1[24][30];
double nominator_tran2[30][30];
double denominator_tran2[30][30];
double new_Objective;
double passed_time;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=29;j++)
{
nominator[i][j] = 0;
nominator_tran1[i][j] = 0;
denominator[i][j] = 0;
denominator_tran1[i][j] = 0;
}
}
for (int i=1;i<=29;i++)
{
for (int j=1;j<=29;j++)
{
denominator_tran2[i][j] = 0;
nominator_tran2[i][j] = 0;
}
}
// Calculate for those O-D pair with direct service
for (int i=1;i<=Route_max;i++)
{
temp = route[i];
temp2 = route[i];
passed_time = 0;
while (temp->next != NULL)
{
temp = temp->next;
}
while (temp2->next->next != NULL)
{
nominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time);
denominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i];
passed_time = passed_time + shortest_time_matrix[temp2->index][temp2->next->index] + 1.5;
temp2 = temp2->next;
}
nominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time);
denominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i];
}
// Calculate for those O-D pair with NO direct service
for (int i=1;i<=Route_max;i++)
{
temp = route[i];
temp2 = route[i];
passed_time = 0;
while (temp->next != NULL)
{
temp = temp->next;
}
while (temp2->next->next != NULL)
{
for (int j=24;j<=28;j++)
{
if (direct_service[temp2->index][j] == false)
{
nominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time- shortest_time_matrix[29][temp->index]);
denominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i];
}
}
passed_time = passed_time + shortest_time_matrix[temp2->index][temp2->next->index] + 1.5;
temp2 = temp2->next;
}
for (int j=24;j<=28;j++)
{
if (direct_service[temp2->index][j] == false)
{
nominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time- shortest_time_matrix[29][temp->index]);
denominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i];
}
}
nominator_tran2[29][temp->index] += num_of_bus[i]/2/total_trip_time[i] * shortest_time_matrix[29][temp->index];
denominator_tran2[29][temp->index] += num_of_bus[i]/2/total_trip_time[i];
}
// debug
cout << endl << "Nominator: " << endl;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
{
cout << nominator[i][j] << " ";
}
cout << endl;
}
cout << endl << "Nominator_tran1: " << endl;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
{
cout << nominator_tran1[i][j] << " ";
}
cout << endl;
}
cout << endl << "Nominator_tran2: " << endl;
for (int i=1;i<=29;i++)
{
for (int j=1;j<=29;j++)
{
cout << nominator_tran2[i][j] << " ";
}
cout << endl;
}
// debug
const double B1 = 80;
const double B2 = 1;
Objective = 0;
// Calculate original objective function value
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
{
if (direct_service[i][j] == true)
{
average_travel_time = (nominator[i][j]+1.0)/denominator[i][j];
Objective = Objective + B2*average_travel_time* demand[i][j];
}
if (direct_service[i][j] == false)
{
average_travel_time = (nominator_tran1[i][j]+1.0)/denominator_tran1[i][j] + (nominator_tran2[29][j]+1.0)/denominator_tran2[29][j];
Objective = Objective + B1 *demand[i][j]+ B2*average_travel_time *demand[i][j];
}
cout << endl << i << "," << j << " Objective function: " << Objective << endl;
}
}
bool flag_frequency_change=true;
// Start finding the optimal frequency
for (int a=1;a<=Route_max;a++)
{
for (int b=a+1;b<=Route_max;b++)
{
// move 1 bus from route[a] to route[b]
flag_frequency_change=true;
while (flag_frequency_change == true && num_of_bus[a]/2.0/total_trip_time[a]*60.0 >= 4.8)
{
num_of_bus[a]--;
num_of_bus[b]++;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=29;j++)
{
nominator[i][j] = 0;
nominator_tran1[i][j] = 0;
denominator[i][j] = 0;
denominator_tran1[i][j] = 0;
}
}
for (int i=1;i<=29;i++)
{
for (int j=1;j<=29;j++)
{
denominator_tran2[i][j] = 0;
nominator_tran2[i][j] = 0;
}
}
// Calculate for those O-D pair with direct service
for (int i=1;i<=Route_max;i++)
{
temp = route[i];
temp2 = route[i];
passed_time = 0;
while (temp->next != NULL)
{
temp = temp->next;
}
while (temp2->next->next != NULL)
{
nominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time);
denominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i];
passed_time = passed_time + shortest_time_matrix[temp2->index][temp2->next->index] + 1.5;
temp2 = temp2->next;
}
nominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time);
denominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i];
}
// Calculate for those O-D pair with NO direct service
for (int i=1;i<=Route_max;i++)
{
temp = route[i];
temp2 = route[i];
passed_time = 0;
while (temp->next != NULL)
{
temp = temp->next;
}
while (temp2->next->next != NULL)
{
for (int j=24;j<=28;j++)
{
if (direct_service[temp2->index][j] == false)
{
nominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time- shortest_time_matrix[29][temp->index]);
denominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i];
}
}
passed_time = passed_time + shortest_time_matrix[temp2->index][temp2->next->index] + 1.5;
temp2 = temp2->next;
}
for (int j=24;j<=28;j++)
{
if (direct_service[temp2->index][j] == false)
{
nominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time- shortest_time_matrix[29][temp->index]);
denominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i];
}
}
nominator_tran2[29][temp->index] += num_of_bus[i]/2/total_trip_time[i] * shortest_time_matrix[29][temp->index];
denominator_tran2[29][temp->index] += num_of_bus[i]/2/total_trip_time[i];
}
new_Objective = 0;
// Calculate new objective function value
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
{
if (direct_service[i][j] == true)
{
average_travel_time = (nominator[i][j]+1.0)/denominator[i][j];
new_Objective = new_Objective + B2*average_travel_time * demand[i][j];
}
if (direct_service[i][j] == false)
{
average_travel_time = (nominator_tran1[i][j]+1.0)/denominator_tran1[i][j] + (nominator_tran2[29][j]+1.0)/denominator_tran2[29][j];
new_Objective = new_Objective + B1 *demand[i][j] + B2*average_travel_time *demand[i][j];
}
}
}
cout << endl << "New Objective function: " << new_Objective << endl;
if (new_Objective < Objective)
{
cout << "Objective function improved! " << endl << "New frequency setting:" << endl;
for (int c=1;c<=Route_max;c++)
{
cout << num_of_bus[c] << " ";
}
cout << endl;
Objective = new_Objective;
}
else if (new_Objective > Objective)
{
cout << "Objective function not improved! " << endl << "New frequency setting:" << endl;
num_of_bus[a]++;
num_of_bus[b]--;
flag_frequency_change = false;
for (int c=1;c<=Route_max;c++)
{
cout << num_of_bus[c] << " ";
}
cout << endl;
}
}
flag_frequency_change = true;
// move 1 bus from route[b] to route[a]
while (flag_frequency_change == true && num_of_bus[b]/2.0/total_trip_time[b]*60.0 >= 4.8)
{
num_of_bus[b]--;
num_of_bus[a]++;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=29;j++)
{
nominator[i][j] = 0;
nominator_tran1[i][j] = 0;
denominator[i][j] = 0;
denominator_tran1[i][j] = 0;
}
}
for (int i=1;i<=29;i++)
{
for (int j=1;j<=29;j++)
{
denominator_tran2[i][j] = 0;
nominator_tran2[i][j] = 0;
}
}
// Calculate for those O-D pair with direct service
for (int i=1;i<=Route_max;i++)
{
temp = route[i];
temp2 = route[i];
passed_time = 0;
while (temp->next != NULL)
{
temp = temp->next;
}
while (temp2->next->next != NULL)
{
nominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time);
denominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i];
passed_time = passed_time + shortest_time_matrix[temp2->index][temp2->next->index] + 1.5;
temp2 = temp2->next;
}
nominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time);
denominator[temp2->index][temp->index] += num_of_bus[i]/2/total_trip_time[i];
}
// Calculate for those O-D pair with NO direct service
for (int i=1;i<=Route_max;i++)
{
temp = route[i];
temp2 = route[i];
passed_time = 0;
while (temp->next != NULL)
{
temp = temp->next;
}
while (temp2->next->next != NULL)
{
for (int j=24;j<=28;j++)
{
if (direct_service[temp2->index][j] == false)
{
nominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time- shortest_time_matrix[29][temp->index]);
denominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i];
}
}
passed_time = passed_time + shortest_time_matrix[temp2->index][temp2->next->index] + 1.5;
temp2 = temp2->next;
}
for (int j=24;j<=28;j++)
{
if (direct_service[temp2->index][j] == false)
{
nominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i]*(total_trip_time[i]-passed_time- shortest_time_matrix[29][temp->index]);
denominator_tran1[temp2->index][j] += num_of_bus[i]/2/total_trip_time[i];
}
}
nominator_tran2[29][temp->index] += num_of_bus[i]/2/total_trip_time[i] * shortest_time_matrix[29][temp->index];
denominator_tran2[29][temp->index] += num_of_bus[i]/2/total_trip_time[i];
}
new_Objective = 0;
// Calculate new objective function value
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
{
if (direct_service[i][j] == true)
{
average_travel_time = (nominator[i][j]+1.0)/denominator[i][j];
new_Objective = new_Objective + B2*average_travel_time *demand[i][j];
}
if (direct_service[i][j] == false)
{
average_travel_time = (nominator_tran1[i][j]+1.0)/denominator_tran1[i][j] + (nominator_tran2[29][j]+1.0)/denominator_tran2[29][j];
new_Objective = new_Objective + B1 *demand[i][j] + B2*average_travel_time *demand[i][j];
}
}
}
cout << endl << "New Objective function: " << new_Objective << endl;
if (new_Objective < Objective)
{
cout << "Objective function improved! " << endl << "New frequency setting:" << endl;
for (int c=1;c<=Route_max;c++)
{
cout << num_of_bus[c]<< " ";
}
cout << endl;
Objective = new_Objective;
}
else if (new_Objective > Objective)
{
cout << "Objective function not improved! " << endl << "New frequency setting:" << endl;
num_of_bus[b]++;
num_of_bus[a]--;
flag_frequency_change = false;
for (int c=1;c<=Route_max;c++)
{
cout << num_of_bus[c] << " ";
}
cout << endl;
}
}
}
}
}
void Crossover_route(chromosome Parent1,chromosome Parent2, chromosome& Child1, chromosome& Child2)
{
int rand1, rand2, temp;
rand1 = rand()%10+1;
rand2 = rand()%10+1;
while (rand2 == rand1)
{
rand2 = rand()%10 +1;
}
if (rand1 > rand2)
{
temp = rand1;
rand1 = rand2;
rand2 = temp;
}
for (int i=1;i<=10;i++)
{
if (i>=rand1 && i<=rand2)
{
deepCopy(Parent2.route[i],Child1.route[i]);
Child1.total_trip_time[i] = Parent2.total_trip_time[i];
deepCopy(Parent1.route[i],Child2.route[i]);
Child2.total_trip_time[i] = Parent1.total_trip_time[i];
}
else
{
deepCopy(Parent1.route[i],Child1.route[i]);
Child1.total_trip_time[i] = Parent1.total_trip_time[i];
deepCopy(Parent2.route[i],Child2.route[i]);
Child2.total_trip_time[i] = Parent2.total_trip_time[i];
}
}
for (int i=1;i<=10;i++)
{
if (i<=6)
{
Child1.num_of_bus[i] = 18;
Child2.num_of_bus[i] = 18;
}
else
{
Child1.num_of_bus[i] = 17;
Child2.num_of_bus[i] = 17;
}
}
}
void Crossover_stop(chromosome Parent1,chromosome Parent2, chromosome& Child1, chromosome& Child2, double shortest_time_matrix[][30])
{
stop* temp;
stop* temp2;
int rand_num2,rand_num3;
bool flag_same_dest = false;
bool array1_10[11];
int len1, len2; // only count no. of intermediate stops
rand_num2 = rand() % 10 + 1;
temp = Parent1.route[rand_num2];
// Find the destination of a random route in parent 1
while (temp->next != NULL)
{
temp = temp->next;
}
for (int i=1;i<=10;i++)
array1_10[i] = false; // Random generation with no repeat
// Randomly find a route in parent 2 which has the same destination
while (flag_same_dest == false)
{
rand_num3 = rand() % 10 + 1;
while (array1_10[rand_num3] == true)
{
rand_num3 = rand() % 10 + 1;
}
array1_10[rand_num3] = true;
temp2 = Parent2.route[rand_num3];
while (temp2->next != NULL)
{
temp2 = temp2->next;
}
if (temp->index == temp2 ->index)
flag_same_dest = true;
}
len1 = length(Parent1.route[rand_num2])-2;
len2 = length(Parent2.route[rand_num3])-2;
// prevent length == 2
while (len1 == 0 || len2 == 0)
{
flag_same_dest = false;
rand_num2 = rand() % 10 + 1;
temp = Parent1.route[rand_num2];
// Find the destination of a random route in parent 1
while (temp->next != NULL)
{
temp = temp->next;
}
for (int i=1;i<=10;i++)
array1_10[i] = false; // Random generation with no repeat
// Randomly find a route in parent 2 which has the same destination
while (flag_same_dest == false)
{
rand_num3 = rand() % 10 + 1;
while (array1_10[rand_num3] == true)
{
rand_num3 = rand() % 10 + 1;
}
array1_10[rand_num3] = true;
temp2 = Parent2.route[rand_num3];
while (temp2->next != NULL)
{
temp2 = temp2->next;
}
if (temp->index == temp2 ->index)
flag_same_dest = true;
}
len1 = length(Parent1.route[rand_num2])-2;
len2 = length(Parent2.route[rand_num3])-2;
}
// Randomly pick a starting node for exchange
int rand_start1, rand_start2;
int exchange_len1, exchange_len2;
rand_start1 = rand()%len1 +1;
rand_start2 = rand()%len2 +1;
exchange_len1 = rand()% (len1-rand_start1+1)+1;
exchange_len2 = rand()% (len2-rand_start2+1)+1;
cout << endl << rand_num2 << " " << len1 << " test9 " << rand_start1 << " " << exchange_len1 << endl;
cout << endl << rand_num3 << " " << len2 << " test8 " << rand_start2 << " " << exchange_len2 << endl;
// Copy Parent1 to Child1 and Copy Parent2 to Child2
for (int i=1;i<=10;i++)
{
deepCopy(Parent1.route[i],Child1.route[i]);
Child1.total_trip_time[i] = Parent1.total_trip_time[i];
deepCopy(Parent2.route[i],Child2.route[i]);
Child2.total_trip_time[i] = Parent2.total_trip_time[i];
}
// Delete the routes that required to do stop crossover
stop *temp3;
while (Child1.route[rand_num2] != NULL)
{
temp3 = Child1.route[rand_num2];
Child1.route[rand_num2] = Child1.route[rand_num2]->next;
delete temp3;
}
Child1.route[rand_num2] = NULL;
Child1.total_trip_time[rand_num2] = 0;
while (Child2.route[rand_num3] != NULL)
{
temp3 = Child2.route[rand_num3];
Child2.route[rand_num3] = Child2.route[rand_num3]->next;
delete temp3;
}
Child2.route[rand_num3] = NULL;
Child2.total_trip_time[rand_num3] = 0;
// Do stop crossover
stop* temp_Parent1_pos;
stop* temp_Parent2_pos;
temp_Parent1_pos = Parent1.route[rand_num2];
temp_Parent2_pos = Parent2.route[rand_num3];
int count_node = 1;
deepCopy_start_from(temp_Parent1_pos,Child1.route[rand_num2],1,rand_start1,count_node);
deepCopy_start_from(temp_Parent2_pos,Child2.route[rand_num3],1,rand_start2,count_node);
for (int i=1;i<=rand_start1;i++)
{
temp_Parent1_pos = temp_Parent1_pos->next;
}
for (int i=1;i<=rand_start2;i++)
{
temp_Parent2_pos = temp_Parent2_pos->next;
}
deepCopy_start_from(temp_Parent2_pos,Child1.route[rand_num2],rand_start1+1,exchange_len2,count_node);
deepCopy_start_from(temp_Parent1_pos,Child2.route[rand_num3],rand_start2+1,exchange_len1,count_node);
for (int i=1;i<=exchange_len1;i++)
{
temp_Parent1_pos = temp_Parent1_pos->next;
}
for (int i=1;i<=exchange_len2;i++)
{
temp_Parent2_pos = temp_Parent2_pos->next;
}
deepCopy_start_from(temp_Parent1_pos,Child1.route[rand_num2],rand_start1+exchange_len2+1,len1+2-(rand_start1+exchange_len1),count_node);
deepCopy_start_from(temp_Parent2_pos,Child2.route[rand_num3],rand_start2+exchange_len1+1,len2+2-(rand_start2+exchange_len2),count_node);
// Delete repeated nodes
int repeated_node = -1;
check_repeated_node(Child1.route[rand_num2],repeated_node);
while (repeated_node != -1)
{
del(Child1.route[rand_num2]->next,repeated_node);
repeated_node = -1;
check_repeated_node(Child1.route[rand_num2],repeated_node);
}
repeated_node = -1;
check_repeated_node(Child2.route[rand_num3],repeated_node);
while (repeated_node != -1)
{
del(Child2.route[rand_num3]->next,repeated_node);
repeated_node = -1;
check_repeated_node(Child2.route[rand_num3],repeated_node);
}
// Calculate total trip time for the route
Calculate_Total_trip_time(Child1.total_trip_time[rand_num2], Child1.route[rand_num2], shortest_time_matrix);
Calculate_Total_trip_time(Child2.total_trip_time[rand_num3], Child2.route[rand_num3], shortest_time_matrix);
// Allocate initial num. of bus
for (int i=1;i<=10;i++)
{
if (i<=6)
{
Child1.num_of_bus[i] = 18;
Child2.num_of_bus[i] = 18;
}
else
{
Child1.num_of_bus[i] = 17;
Child2.num_of_bus[i] = 17;
}
}
}
void deepCopy_start_from(stop* ptr, stop*& copy, int start_from, int numofnodes, int count_node)
{
if (start_from == count_node)
{
int count_node2 = 0;
deepCopy_numofnodes(ptr,copy,numofnodes,count_node2);
}
else deepCopy_start_from(ptr,copy->next,start_from,numofnodes,count_node + 1);
}
void deepCopy_numofnodes(stop* ptr,stop*& copy,int numofnodes, int count_node2)
{
if (count_node2 < numofnodes)
{
copy = new stop;
copy->index = ptr->index;
copy->next = NULL;
deepCopy_numofnodes(ptr->next, copy->next,numofnodes,count_node2+1);
}
}
void check_repeated_node(stop* ptr, int& repeated_node)
{
stop *temp;
temp = ptr;
int check[29];
for (int i=1;i<=28;i++)
check[i] = 0;
while (temp != NULL)
{
check[temp->index]++;
if (check[temp->index]>1)
repeated_node = temp->index;
temp = temp->next;
}
}
void Mutation_insert(stop* route[])
{
int rand_route;
int rand_pos;
int rand_stop;
int len;
rand_route = rand()%10 +1;
bool check[29];
// Check for used stops
for (int i=1;i<=28;i++)
check[i] = false;
stop* temp;
temp = route[rand_route];
while (temp->next != NULL)
{
check[temp->index] = true;
temp = temp->next;
}
// Randomly generate an unused stop
rand_stop = rand()%23+1;
while (check[rand_stop] == true)
{
rand_stop = rand()%23+1;
}
// Randomly select a inserting pos
len = length(route[rand_route]);
rand_pos = rand()% (len-1)+1;
cout << endl << "node "<< rand_stop << " insert to route[" << rand_route << "] at pos" << rand_pos << endl;
InsertAtPos(rand_pos,route[rand_route],rand_stop);
}
void Mutation_remove(stop* route[])
{
int rand_route;
int rand_pos;
int len;
int remove_node;
// Randomly select a route
rand_route = rand()%10 +1;
// Randomly select a removing pos
len = length(route[rand_route]);
// Prevent len == 2
while (len == 2)
{
rand_route = rand()%10 +1;
len = length(route[rand_route]);
}
rand_pos = rand()% (len-2)+2;
// Find the stop at the above pos.
stop* temp;
temp = route[rand_route];
for (int i=1;i<rand_pos;i++)
{
temp = temp->next;
}
remove_node = temp->index;
cout << endl << "route[" << rand_route << "] at pos " << rand_pos << " is removed" << endl;
del(route[rand_route],remove_node);
}
void Mutation_swap(stop* route[])
{
int rand_route1;
int rand_route2;
int rand_pos1;
int rand_pos2;
int len1, len2;
// Randomly select two route
rand_route1 = rand()%10 +1;
rand_route2 = rand()%10 +1;
while (rand_route2 == rand_route1)
{
rand_route2 = rand()%10+1;
}
len1 = length(route[rand_route1]);
len2 = length(route[rand_route2]);
// prevent len == 2
while (len1 == 2 || len2 == 2)
{
rand_route1 = rand()%10 +1;
rand_route2 = rand()%10 +1;
while (rand_route2 == rand_route1)
{
rand_route2 = rand()%10+1;
}
len1 = length(route[rand_route1]);
len2 = length(route[rand_route2]);
}
// Randomly select two pos
rand_pos1 = rand() % len1 + 1;
if (rand_pos1 == 1)
{
rand_pos2 = 1;
}
else if (rand_pos1 == len1)
{
rand_pos2 = len2;
}
else
{
rand_pos2 = rand()% (len2-2)+2;
}
int swap_node1, swap_node2;
// Find the stop at the above pos.
stop* temp1;
temp1 = route[rand_route1];
for (int i=1;i<rand_pos1;i++)
{
temp1 = temp1->next;
}
swap_node1 = temp1->index;
stop* temp2;
temp2 = route[rand_route2];
for (int i=1;i<rand_pos2;i++)
{
temp2 = temp2->next;
}
swap_node2 = temp2->index;
cout << endl << "route[" << rand_route1 << "] at pos " << rand_pos1 << " swaps with " << "route[" << rand_route2 << "] at pos " << rand_pos2 <<endl;
// Do swapping
temp1->index = swap_node2;
temp2->index = swap_node1;
// Check for repeated nodes
// Remove if repeated
int repeated_node = -1;
check_repeated_node(route[rand_route1],repeated_node);
if (repeated_node != -1)
{
del(route[rand_route1]->next,repeated_node);
}
repeated_node = -1;
check_repeated_node(route[rand_route2],repeated_node);
if (repeated_node != -1)
{
del(route[rand_route2]->next,repeated_node);
}
}
void Mutation_transfer(stop* route[])
{
int rand_route1;
int rand_route2;
int rand_pos1;
int rand_pos2;
int len1, len2;
// Randomly select two route
rand_route1 = rand()%10 +1;
rand_route2 = rand()%10 +1;
while (rand_route2 == rand_route1)
{
rand_route2 = rand()%10+1;
}
len1 = length(route[rand_route1]);
len2 = length(route[rand_route2]);
// prevent len == 2
while (len1 == 2 || len2 == 2)
{
rand_route1 = rand()%10 +1;
rand_route2 = rand()%10 +1;
while (rand_route2 == rand_route1)
{
rand_route2 = rand()%10+1;
}
len1 = length(route[rand_route1]);
len2 = length(route[rand_route2]);
}
// Randomly select two pos
rand_pos1 = rand() % (len1-2) + 2;
rand_pos2 = rand() % (len2-2) + 2;
int transfer_node1, transfer_node2;
// Find the stop at the above pos.
stop* temp1;
temp1 = route[rand_route1];
for (int i=1;i<rand_pos1;i++)
{
temp1 = temp1->next;
}
transfer_node1 = temp1->index;
stop* temp2;
temp2 = route[rand_route2];
for (int i=1;i<rand_pos2;i++)
{
temp2 = temp2->next;
}
transfer_node2 = temp2->index;
cout << endl << "node " << transfer_node1 << " from route[" << rand_route1 << "] is transfered to route[" << rand_route2 << "] after the node " << transfer_node2 << endl;
InsertAtPos(rand_pos2, route[rand_route2], transfer_node1);
del(route[rand_route1], transfer_node1);
// Check for repeated nodes
// Remove if repeated
int repeated_node = -1;
check_repeated_node(route[rand_route2],repeated_node);
if (repeated_node != -1)
{
del(route[rand_route2]->next,repeated_node);
}
}
void stop_sequence_improvement(chromosome& Child,double shortest_time_matrix[][30], const int Route_max)
{
int len;
int temp_stop;
stop* temp;
stop* temp2;
bool improved;
double new_total_trip_time;
for (int r=1;r<=Route_max;r++)
{
Calculate_Total_trip_time(Child.total_trip_time[r],Child.route[r],shortest_time_matrix);
len = length(Child.route[r]);
improved = false;
cout << endl << "Route [" << r << "]: " << endl;
for (int i=2;i<=len-2;i++)
{
for (int j=i+1;j<=len-1;j++)
{
temp = Child.route[r];
temp2 = Child.route[r];
// temp points to stop no. j
for (int k=1;k<i;k++)
{
temp = temp->next;
}
for (int k=1;k<j;k++)
{
temp2 = temp2->next;
}
// exchange stop no. j and no. j+1
temp_stop = temp->index;
temp->index = temp2->index;
temp2->index = temp_stop;
Calculate_Total_trip_time(new_total_trip_time,Child.route[r],shortest_time_matrix);
cout << endl << "i:" << i << ", j: " << j << " _ " << new_total_trip_time << endl;
if (new_total_trip_time < Child.total_trip_time[r])
{
// New is better
cout << endl << "Route [" << r << "] exchange node no." << i << " and " << j << endl;
Child.total_trip_time[r] = new_total_trip_time;
improved = true;
}
else
{
temp_stop = temp->index;
temp->index = temp2->index;
temp2->index = temp_stop;
}
}
}
while (improved == true)
{
Calculate_Total_trip_time(Child.total_trip_time[r],Child.route[r],shortest_time_matrix);
len = length(Child.route[r]);
improved = false;
cout << endl << "Route [" << r << "]: " << endl;
for (int i=2;i<=len-2;i++)
{
for (int j=i+1;j<=len-1;j++)
{
temp = Child.route[r];
temp2 = Child.route[r];
// temp points to stop no. j
for (int k=1;k<i;k++)
{
temp = temp->next;
}
for (int k=1;k<j;k++)
{
temp2 = temp2->next;
}
// exchange stop no. j and no. j+1
temp_stop = temp->index;
temp->index = temp2->index;
temp2->index = temp_stop;
Calculate_Total_trip_time(new_total_trip_time,Child.route[r],shortest_time_matrix);
cout << endl << "i:" << i << ", j: " << j << " _ " << new_total_trip_time << endl;
if (new_total_trip_time < Child.total_trip_time[r])
{
// New is better
cout << endl << "Route [" << r << "] exchange node no." << i << " and " << j << endl;
Child.total_trip_time[r] = new_total_trip_time;
improved = true;
}
else
{
temp_stop = temp->index;
temp->index = temp2->index;
temp2->index = temp_stop;
}
}
}
}
}
}
void check_repair(chromosome& Child,double shortest_time_matrix[][30], const int Route_max)
{
int num_of_inter_stop;
double time_on_TSW;
for (int r=1;r<=Route_max;r++)
{
num_of_inter_stop = length(Child.route[r])-2;
time_on_TSW = Calculate_Total_Route_Time_on_TSW(num_of_inter_stop,Child.route[r],shortest_time_matrix);
while (num_of_inter_stop > 8 || time_on_TSW > 35)
{
cout << endl << "route [" << r << "]_ time on TSW: " << time_on_TSW << endl;
repair_operator(Child.route[r],shortest_time_matrix);
num_of_inter_stop = length(Child.route[r])-2;
time_on_TSW = Calculate_Total_Route_Time_on_TSW(num_of_inter_stop,Child.route[r],shortest_time_matrix);
}
}
}
void repair_operator(stop*& ptr,double shortest_time_matrix[][30])
{
stop* temp;
stop* temp2;
temp = NULL;
int len;
int del_save;
int del_stop;
double total_trip_time_1 = 9999;
double new_total_trip_time_1;
len = length(ptr);
for (int i=2;i<=len-1;i++)
{
// Clear temp
while (temp != NULL)
{
temp2 = temp;
temp = temp->next;
delete temp2;
}
temp = NULL;
// Copy ptr to temp
deepCopy(ptr, temp);
// Delete temp's stop no. i
temp2 = temp;
for (int j=1;j<i;j++)
{
temp2 = temp2->next;
}
del_stop = temp2->index;
del(temp,del_stop);
// Check if the new total trip time is reduced
Calculate_Total_trip_time(new_total_trip_time_1,temp,shortest_time_matrix);
if (new_total_trip_time_1 < total_trip_time_1)
{
total_trip_time_1 = new_total_trip_time_1;
del_save = del_stop;
}
}
cout << endl << "Delete node " << del_save << " gives the max. reduction of time" << endl;
del(ptr, del_save);
}
void repair_missing(chromosome& Child,double shortest_time_matrix[][30], const int Route_max, const double Time_max)
{
// count no. of visit
int check[30];
for (int i=1;i<=29;i++)
check[i] = 0;
stop* temp;
for (int r=1;r<=Route_max;r++)
{
temp = Child.route[r];
while (temp != NULL)
{
check[temp->index]++;
temp = temp->next;
}
}
int set_of_check0[24]; // For repairing
int set_of_check2[24]; // For repairing
int index_for_check0; // For repairing
int index_for_check2; // For repairing
double shortest_travel_time_for_repairing; // For repairing
int closest_node; // For repairing
bool flag_replace = false; // For repairing
for (int j=1;j<= 23;j++)
{
set_of_check0[j] = 0;
set_of_check2[j] = 0;
}
index_for_check0 = 1;
index_for_check2 = 1;
for (int j=1;j<=23;j++)
{
if (check[j] == 0)
{
set_of_check0[index_for_check0] = j;
index_for_check0++;
}
if (check[j] > 1)
{
set_of_check2[index_for_check2] = j;
index_for_check2++;
}
}
// Debug
cout << endl << "Missing: " << endl;
for (int j=1;j<index_for_check0;j++)
{
cout << set_of_check0[j] << " ";
}
cout << endl;
for (int j=1;j<index_for_check2;j++)
{
cout << set_of_check2[j] << " ";
}
cout << endl;
//Debug
// Only repair if num of missed nodes <= 1
if (index_for_check0-1 <= 1)
{
for (int j=1;j<index_for_check0;j++)
{
shortest_travel_time_for_repairing = 9999;
closest_node = 99;
for (int k=1;k<index_for_check2;k++)
{
if (shortest_time_matrix[set_of_check0[j]][set_of_check2[k]] < shortest_travel_time_for_repairing)
{
shortest_travel_time_for_repairing = shortest_time_matrix[set_of_check0[j]][set_of_check2[k]];
closest_node = k;
}
}
flag_replace = false;
cout << "Closest node: " << set_of_check2[closest_node] << endl;
for (int a=1;a<=Route_max;a++)
{
replace_node(Child.route[a]->next,Child.route[a],set_of_check2[closest_node],set_of_check0[j],flag_replace,shortest_time_matrix,Time_max);
}
if (flag_replace == true)
{
check[set_of_check2[closest_node]]--;
check[set_of_check0[j]]++;
}
}
}
if (index_for_check0-1 > 1 || (flag_replace == false && index_for_check0-1 == 1))
{
cout << endl << "Repair fails, destroy this child" << endl;
Child.route[1]->index = -1;
}
// Repair destination (route crossover can miss some destination)
int set_of_dest_check0[29];
int set_of_dest_check2[29];
int index_for_dest_check0;
int index_for_dest_check2;
for (int j=24;j<= 28;j++)
{
set_of_dest_check0[j] = 0;
set_of_dest_check2[j] = 0;
}
index_for_dest_check0 = 1;
index_for_dest_check2 = 1;
for (int j=24;j<=28;j++)
{
if (check[j] == 0)
{
set_of_dest_check0[index_for_dest_check0] = j;
index_for_dest_check0++;
}
if (check[j] > 1)
{
set_of_dest_check2[index_for_dest_check2] = j;
index_for_dest_check2++;
}
}
// Debug
for (int j=1;j<index_for_dest_check0;j++)
{
cout << endl << "Missing destination: " << endl;
cout << set_of_dest_check0[j] << " ";
}
cout << endl;
for (int j=1;j<index_for_dest_check2;j++)
{
cout << set_of_dest_check2[j] << " ";
}
cout << endl;
//Debug
if (index_for_dest_check0-1 > 1)
{
cout << endl << "Missing too much destination, destroy this child" << endl;
Child.route[1]->index = -1;
}
int num_of_destination_stop = 0;
int replace_destination;
bool flag_destination_replace = false;
stop* temp9;
// Repair if missing destination == 1
if (index_for_dest_check0-1 == 1)
{
for (int j=1;j<=index_for_dest_check2-1;j++)
{
if (check[set_of_dest_check2[j]] > num_of_destination_stop)
{
num_of_destination_stop = check[set_of_dest_check2[j]];
replace_destination = set_of_dest_check2[j];
}
}
for (int r=1;r<=10 && flag_destination_replace == false;r++)
{
temp9 = Child.route[r];
while (temp9->next != NULL)
{
temp9 = temp9 -> next;
}
if (temp9 -> index == replace_destination)
{
temp9 -> index = set_of_dest_check0[1];
flag_destination_replace = true;
cout << endl << "destination* " << replace_destination << " is replaced by " << set_of_dest_check0[1] << endl;
}
}
}
}
void del_gene(chromosome& parent, const int Route_max)
{
delist(parent.route,Route_max);
for (int i=1;i<=Route_max;i++)
{
parent.num_of_bus[i] = 0;
parent.total_trip_time[i] = 0;
parent.Objective = 999999999;
}
}
void deepCopy_gene(chromosome parent, chromosome& copy, const int Route_max)
{
for (int i=1;i<=Route_max;i++)
{
deepCopy(parent.route[i],copy.route[i]);
copy.num_of_bus[i] = parent.num_of_bus[i];
copy.total_trip_time[i] = parent.total_trip_time[i];
}
copy.Objective = parent.Objective;
for (int i=1;i<=23;i++)
{
for (int j=24;j<=28;j++)
{
copy.direct_service[i][j] = parent.direct_service[i][j];
}
}
}
void Diversity_control(chromosome gene[], const int Route_max)
{
int rank[41];
bool check_rank[41];
for (int i=1; i<=40;i++)
check_rank[i] = false;
for (int i=1; i<=40;i++)
rank[i] = 0;
double lowest_objective = 0;
int lowest_save;
// selection sort according to fitness value (1/objective) (From low objective to high objective)
for (int i=1; i<=40; i++)
{
lowest_objective = 2000000000;
for (int j=1;j<=40;j++)
{
if (check_rank[j] == false)
{
if (gene[j].Objective <= lowest_objective)
{
lowest_objective = gene[j].Objective;
lowest_save = j;
}
}
}
rank[i] = lowest_save;
check_rank[lowest_save] = true;
}
// debug
cout << endl << "Check ranking" << endl;
for (int i=1; i<=40;i++)
cout << rank[i] << " ";
cout << endl;
// debug
// Copy gene to control according to rank
chromosome control[41];
for (int i=1;i<=40;i++)
{
for (int r=1;r<= Route_max;r++)
{
control[i].route[r] = NULL;
control[i].num_of_bus[r] = 0;
control[i].total_trip_time[r] = 0;
}
control[i].Objective = 999999999;
}
for (int i=1;i<=40;i++)
{
deepCopy_gene(gene[rank[i]],control[i],Route_max);
}
// Display 40 controls (Parents+ offspring)
for (int i=1;i<=40;i++)
{
cout << endl << "control[" << i << "] 10 routes:" << endl;
displayallroute(control[i].route,Route_max);
cout << "Num of bus: ";
for (int j=1;j<=Route_max;j++)
cout << control[i].num_of_bus[j] << " ";
cout << endl << "Total trip time: ";
for (int j=1;j<=Route_max;j++)
cout << control[i].total_trip_time[j] << " ";
cout << endl << "Objective: " << control[i].Objective << endl;
}
// Delete all genes
for (int i=1;i<=40;i++)
{
del_gene(gene[i],Route_max);
}
// Copy the best individual to gene[1]
deepCopy_gene(control[1],gene[1],Route_max);
// calculate hamming distance and prob. of survival
const double a = 0.002;
const double c = 0.08;
double h;
int node_pair[11][10][3]; // [route index][node_pair index][the two nodes]
int num_of_node_pair[11]; // length(route)-1;
int new_node_pair[3];
double L1;
// Save the node_pair of the best individual and calculate L for the best individual
stop* temp;
L1 = 0;
for (int r=1;r<=Route_max;r++)
{
num_of_node_pair[r] = length(control[1].route[r])-1;
temp = control[1].route[r];
for (int i=1;i<= num_of_node_pair[r];i++)
{
L1++;
node_pair[r][i][1] = temp->index;
node_pair[r][i][2] = temp->next->index;
temp = temp->next;
}
}
// debug start
cout << endl << "L1: " << L1 << endl;
for (int r=1;r<=Route_max;r++)
{
cout << endl;
for (int i=1;i<= num_of_node_pair[r];i++)
{
cout << node_pair[r][i][1] << " " << node_pair[r][i][2] << ", ";
}
cout << endl;
}
// debug end
int index_for_gene = 1;
double L2;
double prob_survive;
double rand_num;
for (int i=2;i<=40 && index_for_gene <20;i++)
{
if (control[i].route[1]->index != -1)
{
h = L1;
L2 = 0;
for (int r=1;r<=Route_max;r++)
{
temp = control[i].route[r];
// Calculate hamming distance for each route
for (int k=1;k<= length(control[i].route[r])-1;k++)
{
L2++;
h++;
new_node_pair[1] = temp->index;
new_node_pair[2] = temp->next->index;
// Check if the node pair is repeated
for (int j=1; j<=num_of_node_pair[r];j++)
{
if (new_node_pair[1] == node_pair[r][j][1] && new_node_pair[2] == node_pair[r][j][2])
{
h = h-2;
}
}
temp = temp->next;
}
}
// Generate a random number
rand_num = (rand()%1000000+1.0)/1000000.0;
// debug start
prob_survive = pow(((1-c)*h/(L1+L2)+c), a);
cout << endl << "control [" << i << "], L2: " << L2 << ", h: " << h << " , prob: "<< prob_survive << " , rand_num: " << rand_num << endl;
// debug end
if (prob_survive >= rand_num)
{
index_for_gene++;
deepCopy_gene(control[i],gene[index_for_gene],Route_max);
}
else
cout << endl << "control[" << i << "] not survive" << endl;
}
}
for (int i=1;i<=40;i++)
{
del_gene(control[i],Route_max);
}
}
|
/*
ID: stevenh6
TASK: beads
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
int n;
int cutOff = 0;
int evalLeft(string beads) {
char set = 'w';
int count = 0;
for (int i = 0; i < n; i++) {
if (set == 'w') {
set = beads[i];
count++;
} else if (beads[i] == set || beads[i] == 'w') {
count++;
} else {
break;
cutOff = i;
}
}
return count;
}
int evalRight(string beads) {
char set = 'w';
int count = 0;
for (int i = n-1; i >= cutOff; i--) {
if (set == 'w') {
set = beads[i];
count++;
} else if (beads[i] == set || beads[i] == 'w') {
count++;
} else {
break;
}
}
return count;
}
int main() {
ofstream fout ("beads.out");
ifstream fin ("beads.in");
string neck;
fin >> n;
fin >> neck;
int lg = 0;
for (int i = 0; i < n; i++) {
string splyce = neck.substr(i, n - i) + neck.substr(0, i);
cutOff = 0;
int t = evalLeft(splyce) + evalRight(splyce);
if (t > lg) {
lg = t;
}
}
if (lg >= n) {
fout << n << endl;
}
else {
fout << lg << endl;
}
return 0;
}
|
#include <iostream>
#include "triangle.h"
Triangle::Triangle() {
t0 = Vector(0, 0, 0);
t1 = Vector(-1, -1, 0);
t2 = Vector(1, -1, 0);
tnormal = Vector(0, 0, 1);
col.x = col.y = col.z = 1.0f;
spec = 0.4f;
refl = 0.1f;
}
Triangle::Triangle(Vector a0, Vector a1, Vector a2, Vector nor) {
t0 = a0;
t1 = t1;
t2 = a2;
tnormal = nor;
col.x = col.y = col.z = 1.0f;
spec = 0.4f;
refl = 0.05f;
}
void Triangle::setSpec(float spec) {
this->spec = spec;
}
Triangle::Triangle(Vector a0, Vector a1, Vector a2, Vector nor, Color c) {
t0 = a0;
t1 = a1;
t2 = a2;
tnormal = nor;
col.x = c.x;
col.y = c.y;
col.z = c.z;
spec = 0.4f;
refl = 0.05f;
}
Color Triangle::getColor() {
return col;
}
float Triangle::getDiffuse() {
return 1.0f - spec;
}
float Triangle::getRefl() {
return refl;
}
float Triangle::getSpec() {
return spec;
}
void Triangle::setRefl(float refl) {
this->refl = refl;
}
Vector Triangle::getNormal() {
return tnormal;
}
bool Triangle::InTriangle(const Vector& orig, const Vector& dir, float* t, float* u, float* v)
{
Vector E1 = t1 - t0;
Vector E2 = t2 - t0;
Vector P(dir.y*E2.z - dir.z*E2.y, dir.z*E2.x - dir.x*E2.z, dir.x*E2.y - dir.y*E2.x);
float det = E1.dot(P);
Vector T;
if (det >0)
{
T = orig -t0;
}
else
{
T = t0 - orig;
det = -det;
}
if (det < 0.0001f)
return false;
*u = T.dot(P);
if (*u < 0.0f || *u > det)
return false;
Vector Q = T.cross(E1);
*v = dir.x*Q.x + dir.y*Q.y + dir.z*Q.z;;
if (*v < 0.0f || *u + *v > det)
return false;
*t = E2.dot(Q);
float fInvDet = 1.0f / det;
*t *= fInvDet;
*u *= fInvDet;
*v *= fInvDet;
return true;
}
INTERSECTION_TYPE Triangle::intersected(Ray ray, float& dist) {
float cos = tnormal.dot(ray.getDirection());
if (cos != 0)
{
float t = 0.0, u = 0.0, v = 0.0;
if (InTriangle(ray.getOrigin(), ray.getDirection(), &t, &u, &v))
{
if (t>0 && t < dist)
{
dist = t;
return INTERSECTED;
}
}
}
return MISS;
}
Sphere::Sphere() {
t = 1.5;
r = 1.8;
cent = Vector(-1.5, -1.5, 6);
col = Vector(0.85, 0.55, 0.55);
}
Vector Sphere::getCenter() {
return cent;
}
Vector Sphere::getNorm(Vector point){
Vector normal = point - cent;
normal.normalize();
return normal;
}
INTERSECTION_TYPE Sphere::intersected(Ray ray, float &dist) {
float a = ray.getDirection().dot(ray.getDirection());
Vector v = ray.getOrigin() - cent;
float b = 2 * ray.getDirection().dot(v);
float c = v.dot(v) - r * r;
float det = b*b - 4 * a*c;
INTERSECTION_TYPE inter = MISS;
if (det>0)
{
det = sqrt(det);
float t1 = (-b - det) / 2 * a;
float t2 = (-b + det) / 2 * a;
if (t2>0)
{
if (t1<0)
{
if (t2<dist)
{
dist = t2;
inter = INSEC_IN;
}
}
else
{
if (t1<dist)
{
dist = t1;
inter = INTERSECTED;
}
}
}
}
return inter;
}
|
#include "utils.hpp"
#include "achievement_ptts.hpp"
#include "quest_ptts.hpp"
namespace pc = proto::config;
namespace nora {
namespace config {
achievement_ptts& achievement_ptts_instance() {
static achievement_ptts inst;
return inst;
}
void achievement_ptts_set_funcs() {
achievement_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(quest, ptt.quest())) {
CONFIG_ELOG << "achievement table: " << ptt.id() << " quest not exist " << ptt.quest();
}
auto& quest_ptt = PTTS_GET(quest, ptt.quest());
quest_ptt.set__achievement_quest(ptt.id());
};
}
}
}
|
// Copyright (c) 2016 peposso All Rights Reserved.
// Released under the MIT license
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <memory>
#include "xlsx.hpp"
#include "utils.hpp"
#include "yaml_config.hpp"
#include "arg_config.hpp"
#include "handlers.hpp"
#include "validator.hpp"
#define EXCEPTION XLSXCONVERTER_UTILS_EXCEPTION
namespace xlsxconverter {
struct Converter {
static inline
bool truthy(const std::string& s) {
static std::unordered_set<std::string> set = {
"false", "False", "FALSE",
"no", "No", "NO",
"non", "Non", "NON",
"n", "N",
"off", "Off", "OFF",
"null", "Null", "NULL",
"nil", "Nill", "NILL",
"none", "None", "NONE",
"0", "0.0", "",
};
return set.find(s) == set.end();
}
YamlConfig& yaml_config;
bool ignore_relation = false;
bool using_cache = false;
std::vector<boost::optional<Validator>> validators;
std::vector<boost::optional<handlers::RelationMap&>> relations;
inline
explicit Converter(YamlConfig& yaml_config_, bool using_cache_, bool ignore_relation_ = false)
: yaml_config(yaml_config_),
using_cache(using_cache_),
ignore_relation(ignore_relation_) {
for (auto& field : yaml_config.fields) {
if (field.validate == boost::none) {
validators.push_back(boost::none);
} else {
validators.push_back(Validator(field));
}
if (ignore_relation || field.relation == boost::none) {
relations.push_back(boost::none);
} else {
relations.push_back(handlers::RelationMap::find_cache(field.relation.value()));
}
}
if (yaml_config.arg_config.no_cache) {
using_cache = false;
}
}
static inline
std::shared_ptr<xlsx::Workbook> open_workbook(const std::string& path, bool using_cache) {
if (!using_cache) {
return std::make_shared<xlsx::Workbook>(path);
}
static utils::shared_cache<std::string, xlsx::Workbook> cache;
return cache.get_or_emplace(path, path);
}
template<class T>
void run(T& handler) {
auto paths = yaml_config.get_xls_paths();
if (paths.empty()) {
throw EXCEPTION(yaml_config.path, ": target file does not exist.");
}
for (auto& validator : validators) {
if (validator) validator.get().reset();
}
handler.begin();
for (int i = 0; i < paths.size(); ++i) {
auto xls_path = paths[i];
try {
auto book = open_workbook(xls_path, using_cache);
auto& sheet = book->sheet_by_name(yaml_config.target_sheet_name);
auto column_mapping = map_column(sheet, xls_path);
// process data
handle(handler, sheet, column_mapping);
} catch (utils::exception& exc) {
throw EXCEPTION("yaml=", yaml_config.path,
": xls=", xls_path,
": sheet=", yaml_config.target_sheet_name,
": ", exc.what());
}
}
handler.end();
}
inline
std::vector<int> map_column(xlsx::Sheet& sheet, std::string& xls_path) {
std::vector<int> column_mapping;
for (int k = 0; k < yaml_config.fields.size(); ++k) {
auto& field = yaml_config.fields[k];
bool found = false;
for (int i = 0; i < sheet.ncols(); ++i) {;
auto& cell = sheet.cell(yaml_config.row - 1, i);
if (cell.as_str() == field.name) {
column_mapping.push_back(i);
found = true;
break;
}
}
if (!found) {
if (field.optional) {
column_mapping.push_back(-1);
continue;
}
for (int i = 0; i < sheet.ncols(); ++i) {
auto& cell = sheet.cell(yaml_config.row-1, i);
utils::log("cell[", cell.cellname(), "]=", cell.as_str());
}
throw EXCEPTION(yaml_config.path, ": ", xls_path, ": row=", yaml_config.row,
": field{column=", field.column,
",name=", field.name, "}: NOT exists.");
}
}
return column_mapping;
}
template<class T>
void handle(T& handler, xlsx::Sheet& sheet, std::vector<int>& column_mapping) {
if (handler.handler_config.comment_row != boost::none) {
int row = handler.handler_config.comment_row.value() - 1;
handler.begin_comment_row();
for (int k = 0; k < column_mapping.size(); ++k) {
auto& field = yaml_config.fields[k];
if (field.type == YamlConfig::Field::Type::kIsIgnored) continue;
auto i = column_mapping[k];
if (i == -1) {
handler.field(field, std::string());
} else {
auto& cell = sheet.cell(row, i);
handler.field(field, cell.as_str());
}
}
handler.end_comment_row();
}
for (int j = yaml_config.row; j < sheet.nrows(); ++j) {
bool is_empty_line = true;
bool is_ignored = false;
for (int k = 0; k < column_mapping.size(); ++k) {
using CT = xlsx::Cell::Type;
auto& field = yaml_config.fields[k];
auto i = column_mapping[k];
auto& cell = sheet.cell(j, i);
if (i == -1) continue;
if (cell.type != CT::kEmpty) {
is_empty_line = false;
}
if (field.type == YamlConfig::Field::Type::kIsIgnored) {
if (cell.type == CT::kBool) {
is_ignored = cell.as_bool();
}
if (cell.type == CT::kInt || cell.type == CT::kDouble) {
is_ignored = cell.as_int() != 0;
}
if (cell.type == CT::kString) {
is_ignored = truthy(cell.as_str());
}
if (is_ignored) break;
}
}
if (is_empty_line || is_ignored) { continue; }
handler.begin_row();
for (int k = 0; k < column_mapping.size(); ++k) {
auto& field = yaml_config.fields[k];
if (field.type == YamlConfig::Field::Type::kIsIgnored) continue;
auto i = column_mapping[k];
if (i == -1) {;
if (!field.using_default) {
throw EXCEPTION("optional field requires default.");
}
handle_cell_default(handler, field);
} else {
auto& cell = sheet.cell(j, i);
auto& validator = validators[k];
auto& relation = relations[k];
try {
handle_cell(handler, cell, field, validator, relation);
} catch (std::exception& exc) {
throw EXCEPTION("field=", field.column, ": cell[", cell.cellname(), "]=",
"{value=", cell.as_str(), ",type=", cell.type_name(), "}: ",
exc.what());
}
}
}
try {
handler.end_row();
} catch (std::exception& exc) {
throw EXCEPTION("row=", j, ": ", exc.what());
}
}
}
template<class T>
void handle_cell(T& handler, xlsx::Cell& cell, YamlConfig::Field& field,
boost::optional<Validator>& validator,
boost::optional<handlers::RelationMap&>& relation) {
using FT = YamlConfig::Field::Type;
using CT = xlsx::Cell::Type;
switch (field.type) {
case FT::kInt : {
if (field.definition != boost::none) {
auto it = field.definition->find(cell.as_str());
if (it == field.definition->end()) {
throw EXCEPTION("not in definition.");
}
int64_t v = std::stoi(it->second);
if (validator != boost::none) validator.value()(v);
handler.field(field, v);
return;
}
if (cell.type == CT::kInt || cell.type == CT::kDouble) {
auto v = cell.as_int();
if (validator != boost::none) validator.value()(v);
handler.field(field, v);
return;
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
throw EXCEPTION("type error. expect int.");
}
case FT::kFloat: {
if (field.definition != boost::none) {
auto it = field.definition->find(cell.as_str());
if (it == field.definition->end()) {
throw EXCEPTION("not in definition.");
}
double v = std::stod(it->second);
handler.field(field, v);
return;
}
if (cell.type == CT::kInt || cell.type == CT::kDouble) {
handler.field(field, cell.as_double());
return;
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
throw EXCEPTION("type error. expect float.");
}
case FT::kBool: {
if (field.definition != boost::none) {
auto it = field.definition->find(cell.as_str());
if (it == field.definition->end()) {
throw EXCEPTION("not in definition.");
}
auto s = it->second;
bool v = s != "false" && s != "no";
handler.field(field, v);
return;
}
if (cell.type == CT::kBool) {
handler.field(field, cell.as_bool());
return;
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
if (cell.type == CT::kEmpty) {
handler.field(field, false);
return;
}
if (cell.type == CT::kInt || cell.type == CT::kDouble) {
handler.field(field, cell.as_int() != 0);
return;
}
if (cell.type == CT::kString) {
auto v = truthy(cell.as_str());
handler.field(field, v);
return;
}
throw EXCEPTION("type error. expect bool.");
}
case FT::kChar: {
if (field.definition != boost::none) {
auto it = field.definition->find(cell.as_str());
if (it == field.definition->end()) {
throw EXCEPTION("not in definition.");
}
handler.field(field, it->second);
return;
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
auto v = cell.as_str();
if (validator != boost::none) validator.value()(v);
handler.field(field, v);
return;
}
case FT::kDateTime: {
if (field.definition != boost::none) {
throw EXCEPTION("not support datetime definition.");
return;
}
auto tz = yaml_config.arg_config.tz_seconds;
if (cell.type == CT::kDateTime) {
auto time = cell.as_time64(tz);
handler.field(field, utils::dateutil::isoformat64(time, tz));
return;
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
if (cell.type == CT::kString) {
auto time = utils::dateutil::parse64(cell.as_str(), tz);
if (time == utils::dateutil::ntime) {
throw EXCEPTION("parsing datetime error.");
}
handler.field(field, utils::dateutil::isoformat64(time, tz));
return;
}
throw EXCEPTION("type error. expect datetime.");
}
case FT::kAny: {
if (field.definition != boost::none) {
throw EXCEPTION("not support any definition.");
return;
}
if (cell.type == CT::kDateTime) {
auto tz = yaml_config.arg_config.tz_seconds;
auto time = cell.as_time64(tz);
handler.field(field, utils::dateutil::isoformat64(time, tz));
return;
}
if (cell.type == CT::kEmpty) {
if (field.using_default) {
handle_cell_default(handler, field);
return;
}
std::string s = "";
handler.field(field, s);
return;
}
if (cell.type == CT::kBool) {
handler.field(field, cell.as_bool());
return;
}
if (cell.type == CT::kString) {
auto s = cell.as_str();
if (s == "TRUE" || s == "True" || s == "true") {
handler.field(field, true);
return;
} else if (s == "FALSE" || s == "False" || s == "false") {
handler.field(field, false);
return;
} else if (s == "NULL" || s == "Null" || s == "null" ||
s == "NONE" || s == "None" || s == "none") {
handler.field(field, nullptr);
return;
}
handler.field(field, s);
return;
}
if (cell.type == CT::kInt) {
handler.field(field, cell.as_int());
return;
}
if (cell.type == CT::kDouble) {
handler.field(field, cell.as_double());
return;
}
throw EXCEPTION("unknown field.type.");
}
case FT::kUnixTime: {
if (field.definition != boost::none) {
throw EXCEPTION("not support unixtime definition.");
return;
}
auto tz = yaml_config.arg_config.tz_seconds;
if (cell.type == CT::kDateTime) {
auto time = cell.as_time64(tz);
handler.field(field, time);
return;
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
if (cell.type == CT::kString) {
auto time = utils::dateutil::parse64(cell.as_str(), tz);
if (time == utils::dateutil::ntime) {
throw EXCEPTION("parsing datetime error.");
}
handler.field(field, time);
return;
}
throw EXCEPTION("type error. expect datetime.");
}
case FT::kForeignKey: {
if (ignore_relation) return;
if (field.definition != boost::none) {
throw EXCEPTION("not support foreignkey definition.");
return;
}
if (relation == boost::none) {
throw EXCEPTION("requires relation map.");
}
if (cell.type == CT::kEmpty && field.using_default) {
handle_cell_default(handler, field);
return;
}
if (cell.type == CT::kInt && field.relation.value().ignore != INT_MIN) {
auto i = cell.as_int();
if (i == field.relation.value().ignore) {
handler.field(field, cell.as_int());
return;
}
}
auto& relmap = relation.value();
if (relmap.id != field.relation->id) {
throw EXCEPTION("relation maps was broken. id=", relmap.id);
}
#define RELATION_TYPE_EXCEPTION() \
EXCEPTION("invalid relation type pair ", relmap.key_type_name, " -> ", \
relmap.column_type_name)
if (relmap.key_type == FT::kChar) {;
if (relmap.column_type == FT::kInt) {
try {
auto v = relmap.get<int64_t, std::string>(cell.as_str());
if (validator != boost::none) validator.value()(v);
handler.field(field, v);
} catch (std::exception& exc) {
throw EXCEPTION(exc.what());
}
return;
} else {
throw RELATION_TYPE_EXCEPTION();
}
} else if (relmap.key_type == FT::kInt) {
if (cell.type != CT::kInt && cell.type != CT::kDouble) {
throw EXCEPTION("not matched relation key_type.");
}
if (relmap.column_type == FT::kInt) {
try {
auto v = relmap.get<int64_t, int64_t>(cell.as_int());
if (validator != boost::none) validator.value()(v);
handler.field(field, v);
} catch (utils::exception& exc) {
throw EXCEPTION(exc.what());
}
return;
} else {
throw RELATION_TYPE_EXCEPTION();
}
} else {
throw RELATION_TYPE_EXCEPTION();
}
#undef RELATION_TYPE_EXCEPTION
}
case FT::kError: {
throw EXCEPTION("field.type error.");
}
case FT::kIsIgnored: {
return;
}
}
throw EXCEPTION("unknown field error.");
}
template<class T>
void handle_cell_default(T& handler, YamlConfig::Field& field) {
auto& v = field.default_value;
if (v.type() == typeid(int64_t)) {
handler.field(field, boost::any_cast<int64_t>(v));
} else if (v.type() == typeid(double)) {
handler.field(field, boost::any_cast<double>(v));
} else if (v.type() == typeid(bool)) {
handler.field(field, boost::any_cast<bool>(v));
} else if (v.type() == typeid(std::string)) {
handler.field(field, boost::any_cast<std::string>(v));
} else if (v.type() == typeid(std::nullptr_t)) {
handler.field(field, boost::any_cast<std::nullptr_t>(v));
}
}
};
} // namespace xlsxconverter
#undef EXCEPTION
|
#pragma once
#include "../render/Program.h"
#include "../render/ScreenRectangle.h"
#include "../render/FrameBuffer.h"
#include "../render/Texture.h"
#include "../math/FourierTransform_GPU.h"
#include "../scene/Settings.h"
#include "Animator.h"
//--------------------------------------------------------------------------------------------------
// Implements DFT-bases waves simulation (based on Tessendorf, 1999, 2004)
// GPU version.
class AnimatorRDFT_GPU : public Animator
{
public:
virtual void init(const Settings& settings);
virtual void update(double time);
virtual void draw();
virtual void getProgramPaths(std::string& vertex, std::string& fragment);
virtual void setAdditionalUniforms(Program& prg);
protected:
void initSpectrum();
void makeRandomTexture();
void initScreenRects();
void animateSpectrums(double time);
void drawScreenRects();
void performFFTs();
void performFFT(FrameBuffer* src, FrameBuffer* dest);
void renderNormalMap();
private:
Settings settings_;
// screen rectangles
Program programRect_;
ScreenRectangle rectH0_;
ScreenRectangle rectHkt_;
ScreenRectangle rectFS_;
ScreenRectangle rectSlope_;
//Program prgHeightmap_;
ScreenRectangle rectFD_;
ScreenRectangle rectDisp_;
ScreenRectangle rectHeights_;
Program prgHeightmap_;
FrameBuffer h0_;
Program initSpectrum_;
FrameBuffer hkt_;
Program animateHeightSpectrum_;
FrameBuffer h_;
FrameBuffer Fslope_;
Program animateSSpectrum_;
FrameBuffer slope_;
FrameBuffer Fdisp_;
Program animateDSpectrum_;
FrameBuffer disp_;
//
FrameBuffer normalMap_;
Program prgNormalMap_;
//
FFTGPU fft_;
Texture random_;
};
|
/* XMRig
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/tools/String.h"
#include <array>
#include <cstring>
#include <fstream>
#include <thread>
#if __ARM_FEATURE_CRYPTO && !defined(__APPLE__)
# include <sys/auxv.h>
# ifndef __FreeBSD__
# include <asm/hwcap.h>
# else
# include <stdint.h>
# include <machine/armreg.h>
# ifndef ID_AA64ISAR0_AES_VAL
# define ID_AA64ISAR0_AES_VAL ID_AA64ISAR0_AES
# endif
# endif
#endif
#include "backend/cpu/platform/BasicCpuInfo.h"
#include "3rdparty/rapidjson/document.h"
#if defined(XMRIG_OS_UNIX)
namespace xmrig {
extern String cpu_name_arm();
} // namespace xmrig
#elif defined(XMRIG_OS_MACOS)
# include <sys/sysctl.h>
#endif
xmrig::BasicCpuInfo::BasicCpuInfo() :
m_threads(std::thread::hardware_concurrency())
{
m_units.resize(m_threads);
for (int32_t i = 0; i < static_cast<int32_t>(m_threads); ++i) {
m_units[i] = i;
}
# ifdef XMRIG_ARMv8
memcpy(m_brand, "ARMv8", 5);
# else
memcpy(m_brand, "ARMv7", 5);
# endif
# if __ARM_FEATURE_CRYPTO
# if defined(__APPLE__)
m_flags.set(FLAG_AES, true);
# elif defined(__FreeBSD__)
uint64_t isar0 = READ_SPECIALREG(id_aa64isar0_el1);
m_flags.set(FLAG_AES, ID_AA64ISAR0_AES_VAL(isar0) >= ID_AA64ISAR0_AES_BASE);
# else
m_flags.set(FLAG_AES, getauxval(AT_HWCAP) & HWCAP_AES);
# endif
# endif
# if defined(XMRIG_OS_UNIX)
auto name = cpu_name_arm();
if (!name.isNull()) {
strncpy(m_brand, name, sizeof(m_brand) - 1);
}
m_flags.set(FLAG_PDPE1GB, std::ifstream("/sys/kernel/mm/hugepages/hugepages-1048576kB/nr_hugepages").good());
# elif defined(XMRIG_OS_MACOS)
size_t buflen = sizeof(m_brand);
sysctlbyname("machdep.cpu.brand_string", &m_brand, &buflen, nullptr, 0);
# endif
}
const char *xmrig::BasicCpuInfo::backend() const
{
return "basic/1";
}
xmrig::CpuThreads xmrig::BasicCpuInfo::threads(const Algorithm &, uint32_t) const
{
return CpuThreads(threads());
}
rapidjson::Value xmrig::BasicCpuInfo::toJSON(rapidjson::Document &doc) const
{
using namespace rapidjson;
auto &allocator = doc.GetAllocator();
Value out(kObjectType);
out.AddMember("brand", StringRef(brand()), allocator);
out.AddMember("aes", hasAES(), allocator);
out.AddMember("avx2", false, allocator);
out.AddMember("x64", is64bit(), allocator); // DEPRECATED will be removed in the next major release.
out.AddMember("64_bit", is64bit(), allocator);
out.AddMember("l2", static_cast<uint64_t>(L2()), allocator);
out.AddMember("l3", static_cast<uint64_t>(L3()), allocator);
out.AddMember("cores", static_cast<uint64_t>(cores()), allocator);
out.AddMember("threads", static_cast<uint64_t>(threads()), allocator);
out.AddMember("packages", static_cast<uint64_t>(packages()), allocator);
out.AddMember("nodes", static_cast<uint64_t>(nodes()), allocator);
out.AddMember("backend", StringRef(backend()), allocator);
out.AddMember("msr", "none", allocator);
out.AddMember("assembly", "none", allocator);
# ifdef XMRIG_ARMv8
out.AddMember("arch", "aarch64", allocator);
# else
out.AddMember("arch", "aarch32", allocator);
# endif
Value flags(kArrayType);
if (hasAES()) {
flags.PushBack("aes", allocator);
}
out.AddMember("flags", flags, allocator);
return out;
}
|
#ifndef ROOT_THcDriftChamber
#define ROOT_THcDriftChamber
///////////////////////////////////////////////////////////////////////////////
// //
// THcDriftChamber //
// //
///////////////////////////////////////////////////////////////////////////////
#include "TClonesArray.h"
#include "THaNonTrackingDetector.h"
#include "THcHitList.h"
#include "THcDCHit.h"
class THaScCalib;
class THcDriftChamber : public THaNonTrackingDetector, public THcHitList {
public:
THcDriftChamber( const char* name, const char* description = "",
THaApparatus* a = NULL );
virtual ~THcDriftChamber();
virtual Int_t Decode( const THaEvData& );
virtual EStatus Init( const TDatime& run_time );
virtual Int_t CoarseProcess( TClonesArray& tracks );
virtual Int_t FineProcess( TClonesArray& tracks );
virtual Int_t ApplyCorrections( void );
// Int_t GetNHits() const { return fNhit; }
Int_t GetNTracks() const { return fTrackProj->GetLast()+1; }
const TClonesArray* GetTrackHits() const { return fTrackProj; }
friend class THaScCalib;
THcDriftChamber(); // for ROOT I/O
protected:
// Calibration
// Per-event data
// Potential Hall C parameters. Mostly here for demonstration
Int_t fNPlanes;
Int_t* fNWires; // Number of wires per plane
TClonesArray* fTrackProj; // projection of track onto scintillator plane
// and estimated match to TOF paddle
// Useful derived quantities
// double tan_angle, sin_angle, cos_angle;
// static const char NDEST = 2;
// struct DataDest {
// Int_t* nthit;
// Int_t* nahit;
// Double_t* tdc;
// Double_t* tdc_c;
// Double_t* adc;
// Double_t* adc_p;
// Double_t* adc_c;
// Double_t* offset;
// Double_t* ped;
// Double_t* gain;
// } fDataDest[NDEST]; // Lookup table for decoder
void ClearEvent();
void DeleteArrays();
virtual Int_t ReadDatabase( const TDatime& date );
virtual Int_t DefineVariables( EMode mode = kDefine );
ClassDef(THcDriftChamber,0) // Generic hodoscope class
};
////////////////////////////////////////////////////////////////////////////////
#endif
|
//: C10:NamespaceMath.h
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
#ifndef NAMESPACEMATH_H
#define NAMESPACEMATH_H
#include "NamespaceInt.h"
namespace Math {
using namespace Int;
Integer a, b;
Integer divide(Integer, Integer);
// ...
}
#endif // NAMESPACEMATH_H ///:~
|
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <string>
#include <random>
using namespace std;
/*
*** *** Function: kmeans算法的一般实现(C++)
*** *** Author : TheDetial
*** *** Platform: win10+vs2013/ macOs+g++11
*** *** Time : 2021/8/6、2021/8/9
*** *** Result : 已通过
*** *** Website :
*/
/*
Kmeans:无监督聚类
一般实现:仅适用于简单数据聚类
算法步骤:
1、 随机取k个质心(特征值的边界以内);
2、 计算每个数据点距离k个质心的欧氏距离(距离算法的选择会影响到最后的结果);
3、 把每个数据点分配到距离最近的质心,此时数据被分为k个簇;
4、 更新质心:计算每个簇的均值做为该簇的质心;
5、 重复步骤2;
6、 直到每个数据的分配簇后的簇标签不再变化,停止迭代;
*/
//数据点结构体
struct point
{
float x1; //特征1
float x2; //特征2
int label; //label=簇索引,质心更新,label同步更新;
};
//kmeans类
class KMEAN
{
public:
void init(string filepath, int k); //初始化
void kmeansCluster(string savepath); //kmeans主调函数
private:
vector<point> vecData; //存储原始数据
vector<point> vecK; //k个质心坐标和簇索引
vector<int> frontlabel; //更新之前data的label,用于和更新之后比较
float eluDistance(point, point); //欧氏距离
void bubbleSort(vector<float>& vec); //冒泡排序从小到大(边界:求特征最大最小值)
void updataLabel(vector<point>& vecdata, vector<point>& veck, vector<int>& veclabel); //更新数据点的标签为:距离最近质心的标签
void updateK(vector<point>& vecdata, vector<point>& veck); //计算每个簇的平均,并更新质心坐标
bool compareLabel(vector<int>& veclabel, vector<point>& vecdata); //data更新前的lable和更新后的lable对比
bool flagChange=false; //数据点的lable更新前后是否改变的标志位,若true则聚类结束,程序退出
};
|
#include "vulkan_shader.h"
#include "extern\glslang\SPIRV\CInterface\spirv_c_interface.cpp"
static_func bool LoadShader(char *filepath)
{
}
|
/*
* Copyright (c) 2020 sayandipde
* Eindhoven University of Technology
* Eindhoven, The Netherlands
*
* Name : image_signal_processing.cpp
*
* Authors : Sayandip De (sayandip.de@tue.nl)
* Sajid Mohamed (s.mohamed@tue.nl)
*
* Date : March 26, 2020
*
* Function : run cpu profiling for benchmarking
*
* History :
* 26-03-20 : Initial version.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <vector>
#include <numeric>
#include <algorithm>
#include <cmath>
#include "halide_benchmark.h"
//#include "Profiler.h"
std::vector<double> get_normal_dist_tuple(std::vector<double> v){
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(),
std::bind2nd(std::minus<double>(), mean));
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size());
return {mean, stdev};
}
std::vector<std::vector<double>> do_benchmarking(std::function<void()> op){
std::vector<double> iterations;
//std::vector<double> min, max, avg;
double min_t_auto = 0.0;
//for (int j = 0; j < 1; j++) {
// for (int i = 0; i < 1; i++){
for (int j = 0; j < 100; j++) {
for (int i = 0; i < 100; i++){
min_t_auto = Halide::Tools::benchmark(1, 1, [&]() { op(); }); // min_t_auto is in seconds [SD]
iterations.push_back(min_t_auto * 1e3); // ms
}
}
// return {bc_tuple, avg_tuple, wc_tuple};
return {iterations};
}
|
#include <dmsdk/sdk.h>
#include "defos_private.h"
#if defined(DM_PLATFORM_WINDOWS)
#include <atlbase.h>
#include <atlconv.h>
#include <WinUser.h>
#include <Windows.h>
// keep track of window placement when going to/from fullscreen or maximized
static WINDOWPLACEMENT placement = {sizeof(placement)};
// used to check if WM_MOUSELEAVE detected the mouse leaving the window
static bool is_mouse_inside = false;
// original wndproc pointer
static WNDPROC originalProc = NULL;
// original mouse clip rect
static RECT originalRect;
static bool is_cursor_clipped = false;
static POINT lock_point;
static bool is_cursor_locked = false;
static bool is_cursor_visible = true;
static bool is_custom_cursor_loaded;
static HCURSOR custom_cursor;
static HCURSOR original_cursor; // used to restore
// forward declarations
bool set_window_style(LONG_PTR style);
LONG_PTR get_window_style();
LRESULT __stdcall custom_wndproc(HWND hwnd, UINT umsg, WPARAM wp, LPARAM lp);
void restore_window_class();
void subclass_window();
/******************
* exposed functions
******************/
void defos_init()
{
is_mouse_inside = false;
is_cursor_clipped = false;
GetClipCursor(&originalRect); // keep the original clip for restore
original_cursor = GetCursor(); // keep the original cursor
GetWindowPlacement(dmGraphics::GetNativeWindowsHWND(), &placement);
subclass_window();
}
void defos_final()
{
defos_set_cursor_clipped(false);
restore_window_class();
}
void defos_event_handler_was_set(DefosEvent event)
{
}
bool defos_is_fullscreen()
{
return !(get_window_style() & WS_OVERLAPPEDWINDOW);
}
bool defos_is_maximized()
{
return !!IsZoomed(dmGraphics::GetNativeWindowsHWND());
}
bool defos_is_mouse_in_view()
{
return is_mouse_inside;
}
void defos_disable_maximize_button()
{
set_window_style(get_window_style() & ~WS_MAXIMIZEBOX);
}
void defos_disable_minimize_button()
{
set_window_style(get_window_style() & ~WS_MINIMIZEBOX);
}
void defos_disable_window_resize()
{
set_window_style(get_window_style() & ~WS_SIZEBOX);
}
void defos_set_cursor_visible(bool visible)
{
if (visible != is_cursor_visible)
{
is_cursor_visible = visible;
ShowCursor(visible ? TRUE : FALSE);
}
}
bool defos_is_cursor_visible()
{
return is_cursor_visible;
}
// https://blogs.msdn.microsoft.com/oldnewthing/20100412-00/?p=14353/
void defos_toggle_fullscreen()
{
if (defos_is_maximized())
{
defos_toggle_maximized();
}
HWND window = dmGraphics::GetNativeWindowsHWND();
if (!defos_is_fullscreen())
{
MONITORINFO mi = {sizeof(mi)};
if (GetMonitorInfo(MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY), &mi))
{
set_window_style(get_window_style() & ~WS_OVERLAPPEDWINDOW);
GetWindowPlacement(window, &placement);
SetWindowPos(window, HWND_TOP,
mi.rcMonitor.left,
mi.rcMonitor.top,
mi.rcMonitor.right - mi.rcMonitor.left,
mi.rcMonitor.bottom - mi.rcMonitor.top,
SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
}
else
{
set_window_style(get_window_style() | WS_OVERLAPPEDWINDOW);
SetWindowPlacement(window, &placement);
}
}
void defos_toggle_maximized()
{
if (defos_is_fullscreen())
{
defos_toggle_fullscreen();
}
HWND window = dmGraphics::GetNativeWindowsHWND();
if (defos_is_maximized())
{
SetWindowPlacement(window, &placement);
}
else
{
GetWindowPlacement(window, &placement);
ShowWindow(window, SW_MAXIMIZE);
}
}
void defos_set_console_visible(bool visible)
{
::ShowWindow(::GetConsoleWindow(), visible ? SW_SHOW : SW_HIDE);
}
bool defos_is_console_visible()
{
return (::IsWindowVisible(::GetConsoleWindow()) != FALSE);
}
void defos_set_window_size(float x, float y, float w, float h)
{
if (isnan(x))
{
x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
}
if (isnan(y))
{
y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;
}
HWND window = dmGraphics::GetNativeWindowsHWND();
SetWindowPos(window, window, (int)x, (int)y, (int)w, (int)h, SWP_NOZORDER);
}
void defos_set_view_size(float x, float y, float w, float h)
{
if (isnan(x))
{
x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
}
if (isnan(y))
{
y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;
}
RECT rect = {0, 0, (int)w, (int)h};
DWORD style = (DWORD)get_window_style();
// TODO: we are assuming the window have no menu, maybe it is better to expose it as parameter later
AdjustWindowRect(&rect, style, false);
HWND window = dmGraphics::GetNativeWindowsHWND();
SetWindowPos(window, window, (int)x, (int)y, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER);
}
void defos_set_window_title(const char *title_lua)
{
SetWindowTextW(dmGraphics::GetNativeWindowsHWND(), CA2W(title_lua));
}
WinRect defos_get_window_size()
{
HWND window = dmGraphics::GetNativeWindowsHWND();
WINDOWPLACEMENT frame = {sizeof(placement)};
GetWindowPlacement(window, &frame);
WinRect rect;
rect.x = (float)frame.rcNormalPosition.left;
rect.y = (float)frame.rcNormalPosition.top;
rect.w = (float)(frame.rcNormalPosition.right - frame.rcNormalPosition.left);
rect.h = (float)(frame.rcNormalPosition.bottom - frame.rcNormalPosition.top);
return rect;
}
WinRect defos_get_view_size()
{
HWND window = dmGraphics::GetNativeWindowsHWND();
RECT wrect;
GetClientRect(window, &wrect);
POINT pos = {wrect.left, wrect.top};
ClientToScreen(window, &pos);
WINDOWPLACEMENT frame = {sizeof(placement)};
GetWindowPlacement(window, &frame);
WinRect rect;
rect.x = (float)pos.x;
rect.y = (float)pos.y;
rect.w = (float)(wrect.right - wrect.left);
rect.h = (float)(wrect.bottom - wrect.top);
return rect;
}
void defos_set_cursor_pos(float x, float y)
{
SetCursorPos((int)x, (int)y);
}
// move cursor to pos relative to current window
// top-left is (0, 0)
void defos_move_cursor_to(float x, float y)
{
HWND window = dmGraphics::GetNativeWindowsHWND();
RECT wrect;
GetClientRect(window, &wrect);
int tox = wrect.left + (int)x;
int toy = wrect.top + (int)y;
POINT pos = {tox, toy};
ClientToScreen(window, &pos);
SetCursorPos(pos.x, pos.y);
}
void defos_set_cursor_clipped(bool clipped)
{
is_cursor_clipped = clipped;
if (clipped)
{
HWND window = dmGraphics::GetNativeWindowsHWND();
RECT wrect;
GetClientRect(window, &wrect);
POINT left_top = {wrect.left, wrect.top};
POINT right_bottom = {wrect.right, wrect.bottom};
ClientToScreen(window, &left_top);
ClientToScreen(window, &right_bottom);
wrect.left = left_top.x;
wrect.top = left_top.y;
wrect.right = right_bottom.x;
wrect.bottom = right_bottom.y;
ClipCursor(&wrect);
}
else
{
ClipCursor(&originalRect);
}
}
bool defos_is_cursor_clipped()
{
return is_cursor_clipped;
}
void defos_set_cursor_locked(bool locked)
{
if (!is_cursor_locked && locked)
{
GetCursorPos(&lock_point);
}
is_cursor_locked = locked;
}
bool defos_is_cursor_locked()
{
return is_cursor_locked;
}
void defos_update() {
if (is_cursor_locked) {
SetCursorPos(lock_point.x, lock_point.y);
}
}
// path of the cursor file,
// for defold it we can save the cursor file to the save folder or use bundle resources,
// then pass the path to this function to load
void defos_set_custom_cursor_win(const char *filename)
{
custom_cursor = LoadCursorFromFile(_T(filename));
SetCursor(custom_cursor);
is_custom_cursor_loaded = true;
}
static LPCTSTR get_cursor(DefosCursor cursor);
void defos_set_cursor(DefosCursor cursor)
{
custom_cursor = LoadCursor(NULL, get_cursor(cursor));
SetCursor(custom_cursor);
is_custom_cursor_loaded = true;
}
void defos_reset_cursor()
{
// here we do not need to set cursor again, as we already ignore that in winproc
is_custom_cursor_loaded = false;
}
/********************
* internal functions
********************/
static LPCTSTR get_cursor(DefosCursor cursor) {
switch (cursor) {
case DEFOS_CURSOR_ARROW:
return IDC_ARROW;
case DEFOS_CURSOR_HAND:
return IDC_HAND;
case DEFOS_CURSOR_CROSSHAIR:
return IDC_CROSS;
case DEFOS_CURSOR_IBEAM:
return IDC_IBEAM;
default:
return IDC_ARROW;
}
}
static bool set_window_style(LONG_PTR style)
{
return SetWindowLongPtrA(dmGraphics::GetNativeWindowsHWND(), GWL_STYLE, style) != 0;
}
static LONG_PTR get_window_style()
{
return GetWindowLongPtrA(dmGraphics::GetNativeWindowsHWND(), GWL_STYLE);
}
static void subclass_window()
{
// check if we already subclass the window
if (originalProc)
{
return;
}
HWND window = dmGraphics::GetNativeWindowsHWND();
originalProc = (WNDPROC)SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)&custom_wndproc); // keep original proc
if (originalProc == NULL)
{
DWORD error = GetLastError();
dmLogError("Error while subclassing current window: %d\n", error);
}
}
static void restore_window_class()
{
if (originalProc != NULL)
{
HWND window = dmGraphics::GetNativeWindowsHWND();
SetWindowLongPtr(window, GWLP_WNDPROC, (LONG_PTR)originalProc);
originalProc = NULL;
}
}
// replaced wndproc to cutomize message processing
static LRESULT __stdcall custom_wndproc(HWND hwnd, UINT umsg, WPARAM wp, LPARAM lp)
{
// NOTE: we do not handle any event here, so they will be processed by the default wndproc callback
switch (umsg)
{
case WM_MOUSEMOVE:
if (!is_mouse_inside)
{
is_mouse_inside = true;
defos_emit_event(DEFOS_EVENT_MOUSE_ENTER);
TRACKMOUSEEVENT tme = {sizeof(tme)};
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = hwnd;
TrackMouseEvent(&tme);
}
break;
case WM_MOUSELEAVE:
is_mouse_inside = false;
defos_emit_event(DEFOS_EVENT_MOUSE_LEAVE);
break;
case WM_SETCURSOR:
if (is_custom_cursor_loaded)
{
SetCursor(custom_cursor);
return TRUE;
}
break;
case WM_SIZE:
if (is_cursor_locked)
{
defos_set_cursor_locked(true);
}
break;
}
if (originalProc != NULL)
return CallWindowProc(originalProc, hwnd, umsg, wp, lp);
else
return 0;
}
#endif
|
#include "Mage.h"
size_t MageHealth[] = { 0, 15, 100, 20, 24, 28, 30, 31, 33, 35, 37, 42, 47, 55, 60, 65, 71, 80, 81, 82, 85 };
size_t MageAttack[] = { 0, 15, 17, 19, 21, 25, 29, 34, 37, 40, 44, 50, 56, 64, 66, 70, 75, 80, 83, 84, 89 };
float MageDefence[] = { 0.f, 1.0f, 1.4f, 1.8f, 2.2f, 2.6f, 3.0f, 4.f, 4.4f, 4.8f, 5.2f, 5.6f, 6.0f, 7.0f, 7.6f, 8.2f, 8.8f, 9.4f, 10.f, 10.f, 10.f };
size_t ExperienceNeed[] = {0, 0, 10, 30, 55, 70, 100, 130, 165, 200, 240, 285, 325, 370, 420, 475, 530, 590, 650, 720};
Mage::Mage()
{
NormalAttackmultiplier = 0.50f;
Name = "Mage";
}
Mage::~Mage()
{
for (vector<Skill*>::iterator it = SkillList.begin(); it != SkillList.end(); it++)
{
if ((*it) != nullptr)
{
delete (*it);
(*it) = nullptr;
}
}
}
void Mage::Init(int Level)
{
SetisPressed(false);
SetisSelected(false);
for (int i = 0; i < Level; i++)
{
LevelUp(true);
}
}
void Mage::LevelUp(bool init)
{
if (init)
Level++;
else
{
if (ExperiencePoints > ExperienceNeed[Level + 1])
Level++;
else
return;
}
ExperiencePoints = (float)ExperienceNeed[Level];
SetHealth(MageHealth[Level]);
SetMaxHealth(MageHealth[Level]);
SetAttack(MageAttack[Level]);
SetDefence((size_t)MageDefence[Level]);
SetDamageMitigation();
if (Level <= 10)
{
Skill* skill = new Skill();
if (Level == 10)
{
skill->SetName("Ars Arcanum");
skill->SetActionCost(100);
skill->SetMaxTurnCooldown(6);
skill->SetStatusEffect(2, "Bleed");
skill->SetStatusEffect(2, "Debuff");
skill->SetRequiredPosition(1, true);
skill->SetRequiredPosition(2, true);
for (int i = 0; i < 3; i++)
{
skill->SetSelectableTarget(i, true);
}
SkillList.push_back(skill);
}
else if (Level == 5)
{
skill->SetName("Miasmic Cloud");
skill->SetActionCost(40);
skill->SetMaxTurnCooldown(2);
skill->SetStatusEffect(3, "Debuff");
skill->SetRequiredPosition(1, true);
skill->SetRequiredPosition(2, true);
for (int i = 0; i < 3; i++)
{
skill->SetSelectableTarget(i, true);
}
SkillList.push_back(skill);
}
else if (Level == 4)
{
skill->SetName("Unholy Incantation");
skill->SetActionCost(40);
skill->SetMaxTurnCooldown(2);
//skill->SetShiftPosition()
skill->SetRequiredPosition(1, true);
skill->SetRequiredPosition(2, true);
skill->SetSelectableTarget(2, true);
skill->SetStatusEffect(1, "Debuff");
SkillList.push_back(skill);
}
else if (Level == 1)
{
skill->SetName("Basic Attack");
skill->SetActionCost(20);
for (size_t i = 0; i < 3; i++)
{
skill->SetRequiredPosition(i, true);
}
skill->SetSelectableTarget(0, true);
skill->SetSelectableTarget(1, true);
SkillList.push_back(skill);
// Magic Bolt
skill = new Skill();
skill->SetName("Magic Bolt");
skill->SetActionCost(30);
skill->SetMaxTurnCooldown(1);
skill->SetRequiredPosition(1, true);
skill->SetRequiredPosition(2, true);
for (size_t i = 0; i < 3; i++)
{
skill->SetSelectableTarget(i, true);
}
SkillList.push_back(skill);
skill = new Skill();
skill->SetName("Blinding Flash");
skill->SetActionCost(35);
skill->SetStatusEffect(1, "Stun");
skill->SetMaxTurnCooldown(1);
for (size_t i = 0; i < 3; i++)
{
skill->SetRequiredPosition(i, true);
skill->SetSelectableTarget(i, true);
}
SkillList.push_back(skill);
}
else
{
delete skill;
skill = nullptr;
}
}
for (vector<Skill*>::iterator it = SkillList.begin(); it != SkillList.end(); it++)
{
Skill* SkillItr = (*it);
if (SkillItr->GetName() == "Ars Arcanum")
SkillItr->SetDamage((int)(Attack * 1.4));
else if (SkillItr->GetName() == "Unholy Incantation")
SkillItr->SetDamage((int)(Attack * 0.2));
else if (SkillItr->GetName() == "Blinding Flash")
SkillItr->SetDamage((int)(Attack * 0.15));
else if (SkillItr->GetName() == "Magic Bolt")
SkillItr->SetDamage((int)(Attack * 0.75));
else if (SkillItr->GetName() == "Basic Attack")
SkillItr->SetDamage((int)(Attack * 0.5));
}
}
void Mage::Update(double dt)
{
}
|
/*
--------------------------------------------------------------------
CS215-401 Lab Exam 1 Practice - 401
Andrew Cassidy
--------------------------------------------------------------------
*/
#include<iostream>
#include<string>
using namespace std;
int main() {
// Problem 1 variables.
string stateInput;
bool validInput;
// Problem 2 variables.
// Problem 3 variables.
// Problem 4 variables.
// Problem 1.
cout << "Question 1:" << endl;
// Get state name input.
cout << "Enter state abbreviation <KY, OH, IN, TN, WV>: ";
cin >> stateInput;
while (validInput != true) {
// stateInput input validation.
stateInput = toupper(stateInput);
if ((stateInput != "KY") & (stateInput != "OH") & (stateInput != "IN") & (stateInput != "TN") & (stateInput != "WV")) {
cout << "Invalid entry!" << endl;
cout << "Enter state abbreviation <KY, OH, IN, TN, WV>: ";
cin >> stateInput;
stateInput = toupper(stateInput);
}
else {
// Print out state associated with abbreviation.
if (stateInput == "KY") cout << "Kentucky" << endl;
else if (stateInput == "OH") cout << "Ohio" << endl;
else if (stateInput == "IN") cout << "Indiana" << endl;
else if (stateInput == "TN") cout << "Tennessee" << endl;
else cout << "West Virginia" << endl;
// Get out of while loop.
validInput = true;
}
}
// Problem 2.
}
|
/*
* SpaceInvaders.cpp
*
* Created: 07.08.2015 21:41:01
* Author: Tobias Nuss
*/
#include <stdint.h>
#include "MyLedMatrix.h"
#ifndef __SPACEINVADERS_H__
#define __SPACEINVADERS_H__
class SpaceInvaders : public MyLedMatrix
{
public:
SpaceInvaders(char qb, uint8_t h, uint8_t w, uint8_t l, uint8_t p, uint8_t t=NEO_GRB + NEO_KHZ800);
~SpaceInvaders();
void Restart();
int ReadSerial();
void MoveInvaders();
void MoveSpaceship();
void Shot();
int Game();
private:
bool m_quit;
uint8_t m_maxleds;
uint8_t m_width, m_height;
uint8_t m_fire;
int8_t m_turn;
uint8_t m_xStart, m_yStart;
uint8_t m_xOldSsPos;
uint8_t m_xSpaceShip, m_ySpaceShip;
uint8_t m_bullets, m_bulletPos, m_shotPos;
// Matrix Definition
#define cols 12
#define rows 10
#define leftLimit 0
#define rightLimit 11
#define topLimit 0
#define bottomLimit 9
int currentMatrix[rows][cols];
}; //SpaceInvaders
#endif //__SPACEINVADERS_H__
|
#ifndef ITEM_H
# define ITEM_H
# include "dice.h"
# include "dungeon.h"
class item {
public:
char symbol;
pair_t position;
int color;
int weight;
int hitpoints;
int damage;
int attribute;
int value;
int dodge;
int defence;
int speed;
int rarity;
bool artifact;
};
#endif
|
#ifndef AWS_REFERENCE_CPP
#define AWS_REFERENCE_CPP
/*
* aws/parser.cpp
* AwesomeScript Reference
* Author: Dominykas Djacenka
* Email: Chaosteil@gmail.com
*/
/* ==============================================================================
* R E F E R E N C E CLASS
* ============================================================================*/
#include "reference.h"
using namespace AwS;
/* ==============================================================================
* P U B L I C M E T H O D S
* ============================================================================*/
template<class T> Reference<T>::Reference(){
}
template<class T> Reference<T>::~Reference(){
// First we completely clean the declared list
_declared.clear();
// Then we completely clean the reference list
_referenced.clear();
}
template<class T> typename Reference<T>::ReferenceStatus Reference<T>::addDeclaration(const T item){
// Add to declared items. If already declared, return. Else, add declaration.
if(isDeclared(item) == IsDeclared)
return AlreadyDeclared;
_declared.push_back(item);
// Not returned, check if is referenced. Remove all references.
_referenced.remove(item);
return IsDeclared;
}
template<class T> typename Reference<T>::ReferenceStatus Reference<T>::addReference(const T item){
// Check if declared. If already declared, return.
if(isDeclared(item) == IsDeclared)
return AlreadyDeclared;
// Not returned, check if referenced. If not, add to list.
if(_isReferenced(item) == NotReferenced){
_referenced.push_back(item);
}
return IsReferenced;
}
template<class T> typename Reference<T>::ReferenceStatus Reference<T>::isDeclared(const T& item) const{
// We check each item if it's in the declaration list
for(typename std::list<T>::const_iterator i = _declared.begin(); i != _declared.end(); ++i){
if(*i == item)
return IsDeclared;
}
return NotDeclared;
}
template<class T> const std::list<T>* Reference<T>::getDeclarations() const{
return &_declared;
}
template<class T> const std::list<T>* Reference<T>::getReferences() const{
return &_referenced;
}
/* ==============================================================================
* P R I V A T E M E T H O D S
* ============================================================================*/
template<class T> typename Reference<T>::ReferenceStatus Reference<T>::_isReferenced(const T& item) const{
// We check if the variable is referenced
for(typename std::list<T>::const_iterator i = _referenced.begin(); i != _referenced.end(); ++i){
if(*i == item)
return IsReferenced;
}
// If the variable is not referenced, it can still be declared
if(isDeclared(item) != IsDeclared)
return NotReferenced;
else
return IsDeclared;
}
#endif
|
// Created on: 1991-07-23
// Created by: Christophe MARION
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepPrim_OneAxis_HeaderFile
#define _BRepPrim_OneAxis_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <BRepPrim_Builder.hxx>
#include <gp_Ax2.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Face.hxx>
class gp_Pnt2d;
//! Algorithm to build primitives with one axis of
//! revolution.
//!
//! The revolution body is described by :
//!
//! A coordinate system (Ax2 from gp). The Z axis is
//! the rotational axis.
//!
//! An Angle around the Axis, When the Angle is 2*PI
//! the primitive is not limited by planar faces. The
//! U parameter range from 0 to Angle.
//!
//! A parameter range VMin, VMax on the meridian.
//!
//! A meridian : The meridian is a curve described by
//! a set of deferred methods.
//!
//! The topology consists of A shell, Faces, Wires,
//! Edges and Vertices. Methods are provided to build
//! all the elements. Building an element implies the
//! automatic building of all its sub-elements.
//!
//! So building the shell builds everything.
//!
//! There are at most 5 faces :
//!
//! - The LateralFace.
//!
//! - The TopFace and the BottomFace.
//!
//! - The StartFace and the EndFace.
class BRepPrim_OneAxis
{
public:
DEFINE_STANDARD_ALLOC
//! The MeridianOffset is added to the parameters on
//! the meridian curve and to the V values of the
//! pcurves. This is used for the sphere for example,
//! to give a range on the meridian edge which is not
//! VMin, VMax.
Standard_EXPORT void SetMeridianOffset (const Standard_Real MeridianOffset = 0);
//! Returns the Ax2 from <me>.
Standard_EXPORT const gp_Ax2& Axes() const;
Standard_EXPORT void Axes (const gp_Ax2& A);
Standard_EXPORT Standard_Real Angle() const;
Standard_EXPORT void Angle (const Standard_Real A);
Standard_EXPORT Standard_Real VMin() const;
Standard_EXPORT void VMin (const Standard_Real V);
Standard_EXPORT Standard_Real VMax() const;
Standard_EXPORT void VMax (const Standard_Real V);
//! Returns a face with no edges. The surface is the
//! lateral surface with normals pointing outward. The
//! U parameter is the angle with the origin on the X
//! axis. The V parameter is the parameter of the
//! meridian.
Standard_EXPORT virtual TopoDS_Face MakeEmptyLateralFace() const = 0;
//! Returns an edge with a 3D curve made from the
//! meridian in the XZ plane rotated by <Ang> around
//! the Z-axis. Ang may be 0 or myAngle.
Standard_EXPORT virtual TopoDS_Edge MakeEmptyMeridianEdge (const Standard_Real Ang) const = 0;
//! Sets the parametric curve of the edge <E> in the
//! face <F> to be the 2d representation of the
//! meridian.
Standard_EXPORT virtual void SetMeridianPCurve (TopoDS_Edge& E, const TopoDS_Face& F) const = 0;
//! Returns the meridian point at parameter <V> in the
//! plane XZ.
Standard_EXPORT virtual gp_Pnt2d MeridianValue (const Standard_Real V) const = 0;
//! Returns True if the point of parameter <V> on the
//! meridian is on the Axis. Default implementation is
//! Abs(MeridianValue(V).X()) < Precision::Confusion()
Standard_EXPORT virtual Standard_Boolean MeridianOnAxis (const Standard_Real V) const;
//! Returns True if the meridian is closed. Default
//! implementation is
//! MeridianValue(VMin).IsEqual(MeridianValue(VMax),
//! Precision::Confusion())
Standard_EXPORT virtual Standard_Boolean MeridianClosed() const;
//! Returns True if VMax is infinite. Default
//! Precision::IsPositiveInfinite(VMax);
Standard_EXPORT virtual Standard_Boolean VMaxInfinite() const;
//! Returns True if VMin is infinite. Default
//! Precision::IsNegativeInfinite(VMax);
Standard_EXPORT virtual Standard_Boolean VMinInfinite() const;
//! Returns True if there is a top face.
//!
//! That is neither : VMaxInfinite()
//! MeridianClosed()
//! MeridianOnAxis(VMax)
Standard_EXPORT virtual Standard_Boolean HasTop() const;
//! Returns True if there is a bottom face.
//!
//! That is neither : VMinInfinite()
//! MeridianClosed()
//! MeridianOnAxis(VMin)
Standard_EXPORT virtual Standard_Boolean HasBottom() const;
//! Returns True if there are Start and End faces.
//!
//! That is : 2*PI - Angle > Precision::Angular()
Standard_EXPORT virtual Standard_Boolean HasSides() const;
//! Returns the Shell containing all the Faces of the
//! primitive.
Standard_EXPORT const TopoDS_Shell& Shell();
//! Returns the lateral Face. It is oriented toward
//! the outside of the primitive.
Standard_EXPORT const TopoDS_Face& LateralFace();
//! Returns the top planar Face. It is Oriented
//! toward the +Z axis (outside).
Standard_EXPORT const TopoDS_Face& TopFace();
//! Returns the Bottom planar Face. It is Oriented
//! toward the -Z axis (outside).
Standard_EXPORT const TopoDS_Face& BottomFace();
//! Returns the Face starting the slice, it is
//! oriented toward the exterior of the primitive.
Standard_EXPORT const TopoDS_Face& StartFace();
//! Returns the Face ending the slice, it is oriented
//! toward the exterior of the primitive.
Standard_EXPORT const TopoDS_Face& EndFace();
//! Returns the wire in the lateral face.
Standard_EXPORT const TopoDS_Wire& LateralWire();
//! Returns the wire in the lateral face with the
//! start edge.
Standard_EXPORT const TopoDS_Wire& LateralStartWire();
//! Returns the wire with in lateral face with the end
//! edge.
Standard_EXPORT const TopoDS_Wire& LateralEndWire();
//! Returns the wire in the top face.
Standard_EXPORT const TopoDS_Wire& TopWire();
//! Returns the wire in the bottom face.
Standard_EXPORT const TopoDS_Wire& BottomWire();
//! Returns the wire in the start face.
Standard_EXPORT const TopoDS_Wire& StartWire();
//! Returns the wire in the start face with the
//! AxisEdge.
Standard_EXPORT const TopoDS_Wire& AxisStartWire();
//! Returns the Wire in the end face.
Standard_EXPORT const TopoDS_Wire& EndWire();
//! Returns the Wire in the end face with the
//! AxisEdge.
Standard_EXPORT const TopoDS_Wire& AxisEndWire();
//! Returns the Edge built along the Axis and oriented
//! on +Z of the Axis.
Standard_EXPORT const TopoDS_Edge& AxisEdge();
//! Returns the Edge at angle 0.
Standard_EXPORT const TopoDS_Edge& StartEdge();
//! Returns the Edge at angle Angle. If !HasSides()
//! the StartEdge and the EndEdge are the same edge.
Standard_EXPORT const TopoDS_Edge& EndEdge();
//! Returns the linear Edge between start Face and top
//! Face.
Standard_EXPORT const TopoDS_Edge& StartTopEdge();
//! Returns the linear Edge between start Face and
//! bottom Face.
Standard_EXPORT const TopoDS_Edge& StartBottomEdge();
//! Returns the linear Edge between end Face and top
//! Face.
Standard_EXPORT const TopoDS_Edge& EndTopEdge();
//! Returns the linear Edge between end Face and
//! bottom Face.
Standard_EXPORT const TopoDS_Edge& EndBottomEdge();
//! Returns the edge at VMax. If MeridianClosed() the
//! TopEdge and the BottomEdge are the same edge.
Standard_EXPORT const TopoDS_Edge& TopEdge();
//! Returns the edge at VMin. If MeridianClosed() the
//! TopEdge and the BottomEdge are the same edge.
Standard_EXPORT const TopoDS_Edge& BottomEdge();
//! Returns the Vertex at the Top altitude on the axis.
Standard_EXPORT const TopoDS_Vertex& AxisTopVertex();
//! Returns the Vertex at the Bottom altitude on the
//! axis.
Standard_EXPORT const TopoDS_Vertex& AxisBottomVertex();
//! Returns the vertex (0,VMax)
Standard_EXPORT const TopoDS_Vertex& TopStartVertex();
//! Returns the vertex (angle,VMax)
Standard_EXPORT const TopoDS_Vertex& TopEndVertex();
//! Returns the vertex (0,VMin)
Standard_EXPORT const TopoDS_Vertex& BottomStartVertex();
//! Returns the vertex (angle,VMax)
Standard_EXPORT const TopoDS_Vertex& BottomEndVertex();
Standard_EXPORT virtual ~BRepPrim_OneAxis();
protected:
//! Creates a OneAxis algorithm. <B> is used to build
//! the Topology. The angle defaults to 2*PI.
Standard_EXPORT BRepPrim_OneAxis(const BRepPrim_Builder& B, const gp_Ax2& A, const Standard_Real VMin, const Standard_Real VMax);
BRepPrim_Builder myBuilder;
private:
gp_Ax2 myAxes;
Standard_Real myAngle;
Standard_Real myVMin;
Standard_Real myVMax;
Standard_Real myMeridianOffset;
TopoDS_Shell myShell;
Standard_Boolean ShellBuilt;
TopoDS_Vertex myVertices[6];
Standard_Boolean VerticesBuilt[6];
TopoDS_Edge myEdges[9];
Standard_Boolean EdgesBuilt[9];
TopoDS_Wire myWires[9];
Standard_Boolean WiresBuilt[9];
TopoDS_Face myFaces[5];
Standard_Boolean FacesBuilt[5];
};
#endif // _BRepPrim_OneAxis_HeaderFile
|
/*
replay
Software Library
Copyright (c) 2010-2019 Marius Elvert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef replay_minimal_sphere_hpp
#define replay_minimal_sphere_hpp
#include <list>
#include <replay/vector_math.hpp>
namespace replay
{
/** Incrementaly construct a d-dimensional point that is equidistant to all
input points. The input points are on the boundary of a d-dimensional sphere.
This data structure is numerically robust and will reject point pushes that
degenerate the numerical stability (i.e. that are very close to the existing ball).
The code is based on the paper 'Fast and Robust Smallest Enclosing Balls' by
Bernd Gaertner.
\ingroup Math
*/
template <class RealType, std::size_t d> class equisphere
{
public:
/** Initialize the solver with an error boundary. 1e-15 is a good value to use with floats.
*/
equisphere(RealType epsilon)
: m(0)
, epsilon(epsilon)
{
sqr_radius[0] = RealType(-1);
std::fill_n(center[0], d, RealType(0));
}
/** Get the center of the equisphere.
*/
const RealType* get_center() const
{
return (m > 0) ? center[m - 1] : center[0];
}
/** Get the squared radius of the sphere that is currently equidistant to all constraint points.
*/
RealType get_squared_radius() const
{
return (m > 0) ? sqr_radius[m - 1] : sqr_radius[0];
}
/** Get the number of points currently used as constraints.
*/
std::size_t get_support_count() const
{
return m;
}
/** Remove the last point constraint.
*/
void pop()
{
--m;
}
/** Add a point constraint.
*/
template <class VectorType> bool push(const VectorType& p)
{
// trivial solution
if (m == 0)
{
for (std::size_t i = 0; i < d; ++i)
initial_point[i] = center[0][i] = p[i];
sqr_radius[0] = RealType(0);
}
else
{
using replay::math::square;
// Compute Q_m=p_i-p_0
RealType Q_m[d];
for (std::size_t i = 0; i < d; ++i)
Q_m[i] = p[i] - initial_point[i];
// Compute a new last column in a = Q_B_(m-1)*Q_m
for (std::size_t i = 0; i < m - 1; ++i)
{
float& lhs = a(i, m - 1);
lhs = RealType(0);
for (std::size_t j = 0; j < d; ++j)
lhs += P[i][j] * Q_m[j];
lhs *= (RealType(2.0) / z[i]);
}
// Compute \bar{Q}_m and substract from Q_m
for (std::size_t i = 0; i < m - 1; ++i)
{
for (std::size_t j = 0; j < d; ++j)
Q_m[j] -= a(i, m - 1) * P[i][j];
}
// Copy to P
std::copy(Q_m, Q_m + d, P[m - 1]);
// Compute z_m
z[m - 1] = RealType(0);
for (std::size_t i = 0; i < d; ++i)
z[m - 1] += square(Q_m[i]);
z[m - 1] *= RealType(2);
// Accept this?
if (z[m - 1] < epsilon * sqr_radius[m - 1])
return false;
RealType e = -sqr_radius[m - 1];
for (std::size_t i = 0; i < d; ++i)
e += square(p[i] - center[m - 1][i]);
RealType cf = f[m - 1] = e / z[m - 1];
for (std::size_t i = 0; i < d; ++i)
center[m][i] = center[m - 1][i] + cf * Q_m[i];
sqr_radius[m] = sqr_radius[m - 1] + e * cf / RealType(2);
}
++m;
return true;
}
private:
// (row_size)x(row_size) matrix that has 1 elements on the diagonal, and 0s below the diagonal
template <std::size_t row_size> class upper_unitriangular_matrix
{
public:
RealType operator()(std::size_t r, std::size_t c) const
{
if (r > c)
return RealType(0);
else if (r == c)
return RealType(1);
std::size_t skip = (r + 1) * (r + 2) / 2;
return v[r * row_size + c - skip];
}
RealType& operator()(std::size_t r, std::size_t c)
{
if (r >= c)
throw std::runtime_error("Cannot write to implicitly defined entries.");
std::size_t skip = (r + 1) * (r + 2) / 2;
return v[r * row_size + c - skip];
}
private:
RealType v[((row_size + 1) * row_size) / 2];
};
typedef upper_unitriangular_matrix<d + 1> matrix_type;
RealType sqr_radius[d + 1];
RealType center[d + 1][d];
// first point to be inserted, origin of relative coordinate system
RealType initial_point[d];
// store the difference between Q_i and \bar{Q}_i =: P_i
RealType P[d][d];
RealType z[d];
RealType f[d];
matrix_type a;
std::size_t m;
const RealType epsilon;
};
/** Welzl's randomized minimal ball algorithm.
The code is based on the paper 'Fast and Robust Smallest Enclosing Balls' by
Bernd Gaertner.
It employs the move-to-front heuristic. However, this heuristic
is only 'cheap' for std::list containers - otherwise std::rotate is used.
\ingroup Math
*/
template <class RealType, class VectorType, std::size_t d> class minimal_ball
{
public:
/** Generate a minimal bounding ball.
*/
template <class ContainerType> minimal_ball(ContainerType& p, RealType epsilon)
{
// clear the output data
for (std::size_t i = 0; i < d; ++i)
m_center[i] = RealType(0);
m_square_radius = RealType(0);
// create a solver
equisphere<RealType, d> B(epsilon);
// generate the sphere
mft_ball(p, p.end(), B);
}
/** Test whether the given point is contained in this sphere.
*/
bool contains(const VectorType& v)
{
using replay::math::square;
RealType delta = -m_square_radius;
for (std::size_t j = 0; j < d; ++j)
delta += square(m_center[j] - v[j]);
return delta <= RealType(0);
}
/** Get the center of the minimal ball.
*/
const VectorType& center() const
{
return m_center;
}
/** Get the square radius of the minimal ball.
*/
RealType square_radius() const
{
return m_square_radius;
}
private:
template <class T> static void move_to_front(std::list<T>& c, typename std::list<T>::iterator i)
{
c.splice(c.begin(), c, i);
}
template <class ContainerType> static void move_to_front(ContainerType& c, typename ContainerType::iterator i)
{
std::rotate(c.begin(), i, i + 1);
}
// copy center and square radius from the solver
void update(const equisphere<RealType, d>& B)
{
const RealType* src = B.get_center();
for (std::size_t i = 0; i < d; ++i)
m_center[i] = src[i];
m_square_radius = B.get_squared_radius();
}
template <class ContainerType>
void mft_ball(ContainerType& p, typename ContainerType::iterator e, equisphere<float, d>& B)
{
typedef typename ContainerType::iterator iterator;
// finished yet?
if (B.get_support_count() == d + 1)
{
update(B);
return;
}
// Test all points for inclusion
for (iterator i = p.begin(); i != e;)
{
// move ahead before potentially moving this around
iterator current = i++;
// restart with this point in if it wasn't contained
// and a push is valid
if (!contains(*current) && B.push(*current))
{
// each successful push gives us a new ball
update(B);
mft_ball(p, current, B);
B.pop();
move_to_front(p, current);
}
}
}
VectorType m_center;
RealType m_square_radius;
};
}
#endif // replay_minimal_sphere_hpp
|
#include<bits/stdc++.h>
using namespace std;
int m,n;
int a[101][101];
void input(){
cin >> m >> n;
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
cin >> a[i][j];
}
bool isMaxInRow(int iC, int jC){
int c = a[iC][jC];
for(int i = 0; i < n; i++){
if(a[iC][i] > c)
return false;
}
return true;
}
bool isMinInRow(int iC, int jC){
int c = a[iC][jC];
for(int i = 0; i < n; i++){
if(a[iC][i] < c)
return false;
}
return true;
}
bool isMaxInCol(int iC, int jC){
int c = a[iC][jC];
for(int i = 0; i < m; i++){
if(a[i][jC] > c)
return false;
}
return true;
}
bool isMinInCol(int iC, int jC){
int c = a[iC][jC];
for(int i = 0; i < m; i++){
if(a[i][jC] < c)
return false;
}
return true;
}
int main(){
freopen("YENNGUA.inp", "r", stdin);
freopen("YENNGUA.out", "w", stdout);
input();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(isMinInRow(i,j) && isMaxInCol(i, j))
cout << i+1 << " " << j+1 << endl;
if(isMaxInRow(i, j) && isMinInCol(i, j))
cout << i+1 << " " << j+1 << endl;
}
}
return 0;
}
|
#include <cstdio>
#include <cmath>
#include <iostream>
using namespace std;
#define N 1000
bool flagTable[N];// 第n列有没有
int P[N];// 第N个在P[n]列
int count = 0;
void generateP(int index, int n){ // index 行
if (index == n + 1) {
count ++;
return;
}
for (int x = 1; x <= n; x++) { // 列
if (flagTable[x] == false) {
bool flag = true;
for (int pre = 1; pre < index; pre++) { // 行
if (abs(index - pre) == abs(x - P[pre])) {
flag = false;
break;
}
}
if (flag) {
P[index] = x;
flagTable[x] = true;
generateP(index+1, n);
flagTable[x] = false;
}
}
}
}
int main(){
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
flagTable[i] = false;
P[i] = 0;
}
generateP(1, n);
printf("%d\n", count);
return 0;
}
|
#include<iostream>
using namespace std;
class A
{
int a,b;
public:
A(int i,int j) {a=i;b=j;}
int c;
friend class B;
};
class B
{
public: int min(A x);
};
int B::min(A x)
{
x.c=30;
cout<<x.c<<endl;
return x.a < x.b ? x.a : x.b ;
}
int main()
{
A a(3,4);
B b;
cout<<b.min(a)<<endl;
}
|
#include<iostream>
#include<vector>
using namespace std;
//双指针法
class Solution1 {
public:
int removeDuplicates(vector<int>& nums) {
int i = 0, j; //两个指针i和j,i是慢指针,j是快指针
int len = nums.size();
if (len == 0)
return 0;
//循环扫描整个nums数组,遇到重复项j++跳过,遇到不重复项nums[j]复制到nums[i+1],所以最后0到i都是不重复项
for (j = 1; j < len; j++)
{
//nums[i]!=nums[j]时,就遇到不重复项nums[j],就把nums[j]复制到nums[i+1]
if (nums[i] != nums[j])
{
i++;
nums[i] = nums[j];
}
//只要nums[i]=nums[j],就增加j以跳过重复项
}
//返回i+1个不重复项的个数
return i + 1;
}
};
//删除元素法
class Solution2 {
public:
int removeDuplicates(vector<int>& nums) {
int i = 0;
if (nums.size() == 0)
return 0;
while (i < nums.size() - 1)
{
//遇到重复项用erase函数删除重复项
if (nums[i] == nums[i + 1])
nums.erase(nums.begin() + i);
else
i++;
}
return nums.size();
}
};
int main()
{
Solution2 solute;
vector<int> nums = { 1,1,2,2,3 };
int len = solute.removeDuplicates(nums);
for (int i = 0; i < len; i++)
cout << nums[i] << endl;
return 0;
}
|
// Created on: 1997-03-04
// Created by: Robert COUBLANC
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _AIS_AttributeFilter_HeaderFile
#define _AIS_AttributeFilter_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Quantity_NameOfColor.hxx>
#include <Standard_Real.hxx>
#include <SelectMgr_Filter.hxx>
class SelectMgr_EntityOwner;
class AIS_AttributeFilter;
DEFINE_STANDARD_HANDLE(AIS_AttributeFilter, SelectMgr_Filter)
//! Selects Interactive Objects, which have the desired width or color.
//! The filter questions each Interactive Object in local
//! context to determine whether it has an non-null
//! owner, and if so, whether it has the required color
//! and width attributes. If the object returns true in each
//! case, it is kept. If not, it is rejected.
//! This filter is used only in an open local context.
//! In the Collector viewer, you can only locate
//! Interactive Objects, which answer positively to the
//! filters, which are in position when a local context is open.
class AIS_AttributeFilter : public SelectMgr_Filter
{
public:
//! Constructs an empty attribute filter object.
//! This filter object determines whether selectable
//! interactive objects have a non-null owner.
Standard_EXPORT AIS_AttributeFilter();
//! Constructs an attribute filter object defined by the
//! color attribute aCol.
Standard_EXPORT AIS_AttributeFilter(const Quantity_NameOfColor aCol);
//! Constructs an attribute filter object defined by the line
//! width attribute aWidth.
Standard_EXPORT AIS_AttributeFilter(const Standard_Real aWidth);
//! Indicates that the Interactive Object has the color
//! setting specified by the argument aCol at construction time.
Standard_Boolean HasColor() const { return hasC; }
//! Indicates that the Interactive Object has the width
//! setting specified by the argument aWidth at
//! construction time.
Standard_Boolean HasWidth() const { return hasW; }
//! Sets the color.
void SetColor (const Quantity_NameOfColor theCol)
{
myCol = theCol;
hasC = Standard_True;
}
//! Sets the line width.
void SetWidth (const Standard_Real theWidth)
{
myWid = theWidth;
hasW = Standard_True;
}
//! Removes the setting for color from the filter.
void UnsetColor() { hasC = Standard_False; }
//! Removes the setting for width from the filter.
void UnsetWidth() { hasW = Standard_False; }
//! Indicates that the selected Interactive Object passes
//! the filter. The owner, anObj, can be either direct or
//! user. A direct owner is the corresponding
//! construction element, whereas a user is the
//! compound shape of which the entity forms a part.
//! If the Interactive Object returns Standard_True
//! when detected by the Local Context selector through
//! the mouse, the object is kept; if not, it is rejected.
Standard_EXPORT virtual Standard_Boolean IsOk (const Handle(SelectMgr_EntityOwner)& anObj) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(AIS_AttributeFilter,SelectMgr_Filter)
private:
Quantity_NameOfColor myCol;
Standard_Real myWid;
Standard_Boolean hasC;
Standard_Boolean hasW;
};
#endif // _AIS_AttributeFilter_HeaderFile
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
// 昇順sort
#define sorti(x) sort(x.begin(), x.end())
// 降順sort
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
vector<int> sft;
int digit;
void dfs(int s, int count) {
if (count > digit) return;
int cpy = s;
sft.pb(cpy);
dfs(cpy + pow(10,count) * 3, count+1);
dfs(cpy + pow(10,count) * 5, count+1);
dfs(cpy + pow(10,count) * 7, count+1);
return;
}
int main() {
int n,cpy,res = 0; cin >> n;
cpy = n;
while (cpy > 0) {
digit++;
cpy /= 10;
}
dfs(3,1);
dfs(5,1);
dfs(7,1);
sorti(sft);
for (auto itr : sft) {
bool s,f,t; s = f = t = false;
if (itr > n) break;
int cpy = itr;
while (cpy > 0) {
int dig = cpy % 10;
if (dig == 3) t = true;
if (dig == 5) f = true;
if (dig == 7) s = true;
cpy /= 10;
}
if (s and t and f) res++;
}
cout << res << endl;
}
|
#ifndef WINDOWSAVETEXTFILE_HH_
#define WINDOWSAVETEXTFILE_HH_
#include "WindowSaveFile.hh"
/** A pop-up window to save a text file. */
class WindowSaveTextFile : public WindowSaveFile
{
public:
WindowSaveTextFile(const PG_Widget *parent, const std::string &content)
: WindowSaveFile(parent, "Save Text File"), m_content(content) { }
virtual ~WindowSaveTextFile() { }
protected:
virtual bool write_file()
{
FILE *file = fopen(this->get_filename().data(), "w");
if (file == NULL) {
this->error("Could not open file for writing.", ERROR_NORMAL);
return false;
}
bool ret_val = true;
if (fwrite(this->m_content.data(), sizeof(char), this->m_content.size(), file) != this->m_content.size()){//fprintf(file, "%s", this->m_content.data()) < 0) {
this->error("Could not write text into file.", ERROR_NORMAL);
ret_val = false;
}
fclose(file);
return ret_val;
}
private:
std::string m_content;
};
#endif /*WINDOWSAVETEXTFILE_HH_*/
|
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define FOR(i,n) for(ll i=0;i<n;i++)
#define FOR1(i,n) for(ll i=1;i<n;i++)
#define FORn1(i,n) for(ll i=1;i<=n;i++)
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define mod 1000000007;
using namespace std;
int main() {
// your code goes here
fast;
int n,x;
cin>>n>>x;
int a[n];
float sum=0;
FOR(i,n)
{
cin>>a[i];
sum+=a[i];
}
int mx = INT_MIN, mxend = 0;
for (int i = 0; i < n; i++)
{
mxend = mxend+a[i];
if (mx<mxend)
mx=mxend;
if (mxend< 0)
mxend=0;
}
//cout<<mx<<" ";
float tmp=(float)mx-((float)mx/x);
sum-=tmp;
cout<<sum;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.